diff --git a/internal/sharedtest/custom_attributes.go b/internal/sharedtest/custom_attributes.go index 9194578..0336b37 100644 --- a/internal/sharedtest/custom_attributes.go +++ b/internal/sharedtest/custom_attributes.go @@ -7,8 +7,9 @@ import ( ) const ( - SmallNumberOfCustomAttributes = 2 //nolint:revive - LargeNumberOfCustomAttributes = 20 //nolint:revive + SmallNumberOfCustomAttributes = 2 //nolint:revive + MiddleNumberOfCustomAttributes = 10 //nolint:revive + LargeNumberOfCustomAttributes = 50 ) type NameAndLDValue struct { //nolint:revive diff --git a/ldcontext/builder_benchmark_test.go b/ldcontext/builder_benchmark_test.go index 2ccaf20..7732e87 100644 --- a/ldcontext/builder_benchmark_test.go +++ b/ldcontext/builder_benchmark_test.go @@ -31,7 +31,11 @@ func BenchmarkBuildWithNoCustomAttrs(b *testing.B) { } func BenchmarkBuildWithCustomAttributes(b *testing.B) { - for _, n := range []int{sharedtest.SmallNumberOfCustomAttributes, sharedtest.LargeNumberOfCustomAttributes} { + for _, n := range []int{ + sharedtest.SmallNumberOfCustomAttributes, + sharedtest.MiddleNumberOfCustomAttributes, + sharedtest.LargeNumberOfCustomAttributes, + } { b.Run(fmt.Sprintf("with %d attributes", n), func(b *testing.B) { attrs := sharedtest.MakeCustomAttributeNamesAndValues(n) b.ResetTimer() @@ -46,6 +50,26 @@ func BenchmarkBuildWithCustomAttributes(b *testing.B) { } } +func BenchmarkBuildWithCustomAttributesWithCapacity(b *testing.B) { + for _, n := range []int{ + sharedtest.SmallNumberOfCustomAttributes, + sharedtest.MiddleNumberOfCustomAttributes, + sharedtest.LargeNumberOfCustomAttributes, + } { + b.Run(fmt.Sprintf("with %d attributes", n), func(b *testing.B) { + attrs := sharedtest.MakeCustomAttributeNamesAndValues(n) + b.ResetTimer() + for i := 0; i < b.N; i++ { + builder := NewBuilderWithCapacity("key", n) + for _, a := range attrs { + builder.SetValue(a.Name, a.Value) + } + benchmarkContext = builder.Build() + } + }) + } +} + func BenchmarkBuildWithPrivate(b *testing.B) { for i := 0; i < b.N; i++ { benchmarkContext = NewBuilder("key").Name("name").Private("name").Build() diff --git a/ldcontext/builder_simple.go b/ldcontext/builder_simple.go index 46f24e0..5ec8705 100644 --- a/ldcontext/builder_simple.go +++ b/ldcontext/builder_simple.go @@ -126,6 +126,14 @@ func NewBuilder(key string) *Builder { return b.Key(key) } +// NewBuilderWithCapacity extends the behavior of NewBuilder to pre-allocate capacity for attributes. +func NewBuilderWithCapacity(key string, capacity int) *Builder { + b := &Builder{ + attributes: *ldvalue.ValueMapBuildWithCapacity(capacity), + } + return b.Key(key) +} + // NewBuilderFromContext creates a Builder whose properties are the same as an existing // single context. //