Skip to content

Commit

Permalink
[chore][pkg/resourcetotelemetry] reduce memory usage by call ensure c…
Browse files Browse the repository at this point in the history
…apacity (#29430)

Description:

1. Reduce memory usage by ensure capacity before merge two maps

Link to tracking Issue:

N/A

Testing:

N/A

Documentation:

N/A
  • Loading branch information
philchia authored Nov 21, 2023
1 parent 4ea95dc commit ce88bd3
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
1 change: 1 addition & 0 deletions pkg/resourcetotelemetry/resource_to_telemetry.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ func addAttributesToExponentialHistogramDataPoints(ps pmetric.ExponentialHistogr
}

func joinAttributeMaps(from, to pcommon.Map) {
to.EnsureCapacity(from.Len() + to.Len())
from.Range(func(k string, v pcommon.Value) bool {
v.CopyTo(to.PutEmpty(k))
return true
Expand Down
70 changes: 70 additions & 0 deletions pkg/resourcetotelemetry/resource_to_telemetry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
package resourcetotelemetry

import (
"fmt"
"testing"

"github.com/stretchr/testify/assert"
"go.opentelemetry.io/collector/pdata/pcommon"

"github.com/open-telemetry/opentelemetry-collector-contrib/internal/coreinternal/testdata"
)
Expand Down Expand Up @@ -65,3 +67,71 @@ func TestConvertResourceToAttributesAllDataTypesEmptyDataPoint(t *testing.T) {
assert.Equal(t, 0, md.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(6).ExponentialHistogram().DataPoints().At(0).Attributes().Len())

}

func BenchmarkJoinAttributes(b *testing.B) {
type args struct {
from int
to int
}
tests := []struct {
name string
args args
}{
{
name: "merge 10 into 10",
args: args{
from: 10,
to: 10,
},
},
{
name: "merge 10 into 20",
args: args{
from: 10,
to: 20,
},
},
{
name: "merge 20 into 10",
args: args{
from: 20,
to: 10,
},
},
{
name: "merge 30 into 10",
args: args{
from: 30,
to: 10,
},
},
{
name: "merge 10 into 30",
args: args{
from: 10,
to: 30,
},
},
}
b.ReportAllocs()
for _, tt := range tests {
b.Run(tt.name, func(b *testing.B) {
b.ResetTimer()
from := initMetricAttributes(tt.args.from, 0)
for i := 0; i < b.N; i++ {
to := initMetricAttributes(tt.args.to, tt.args.from)
joinAttributeMaps(from, to)
}
})
}

}

func initMetricAttributes(capacity int, idx int) pcommon.Map {
dest := pcommon.NewMap()
dest.EnsureCapacity(capacity)
for i := 0; i < capacity; i++ {
dest.PutStr(fmt.Sprintf("label-name-for-index-%d", i+idx), fmt.Sprintf("label-value-for-index-%d", i+idx))
}
return dest
}

0 comments on commit ce88bd3

Please sign in to comment.