diff --git a/addrs/module_instance.go b/addrs/module_instance.go index 7a5c03a6e..396d5f6e0 100644 --- a/addrs/module_instance.go +++ b/addrs/module_instance.go @@ -1,8 +1,8 @@ package addrs import ( - "bytes" "fmt" + "strings" "github.com/hashicorp/hcl/v2" "github.com/hashicorp/hcl/v2/hclsyntax" @@ -251,7 +251,17 @@ func (m ModuleInstance) Parent() ModuleInstance { // // The address of the root module has the empty string as its representation. func (m ModuleInstance) String() string { - var buf bytes.Buffer + if len(m) == 0 { + return "" + } + // Calculate minimal necessary space (no instance keys). + l := 0 + for _, step := range m { + l += len(step.Name) + } + buf := strings.Builder{} + // 8 is len(".module.") which separates entries. + buf.Grow(l + len(m)*8) sep := "" for _, step := range m { buf.WriteString(sep) diff --git a/addrs/module_instance_test.go b/addrs/module_instance_test.go index c36e9952d..2334f28ff 100644 --- a/addrs/module_instance_test.go +++ b/addrs/module_instance_test.go @@ -77,3 +77,17 @@ func TestModuleInstanceEqual_false(t *testing.T) { }) } } + +func BenchmarkStringShort(b *testing.B) { + addr, _ := ParseModuleInstanceStr(`module.foo`) + for n := 0; n < b.N; n++ { + addr.String() + } +} + +func BenchmarkStringLong(b *testing.B) { + addr, _ := ParseModuleInstanceStr(`module.southamerica-brazil-region.module.user-regional-desktops.module.user-name`) + for n := 0; n < b.N; n++ { + addr.String() + } +}