Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance: string builder speedup for Module.String() #31293

Merged
merged 3 commits into from Jun 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 15 additions & 4 deletions internal/addrs/module.go
Expand Up @@ -33,11 +33,22 @@ func (m Module) String() string {
if len(m) == 0 {
return ""
}
var steps []string
for _, s := range m {
steps = append(steps, "module", s)
// Calculate necessary space.
l := 0
for _, step := range m {
l += len(step)
}
return strings.Join(steps, ".")
buf := strings.Builder{}
// 8 is len(".module.") which separates entries.
buf.Grow(l + len(m)*8)
sep := ""
for _, step := range m {
buf.WriteString(sep)
buf.WriteString("module.")
buf.WriteString(step)
sep = "."
}
return buf.String()
}

func (m Module) Equal(other Module) bool {
Expand Down
39 changes: 39 additions & 0 deletions internal/addrs/module_test.go
Expand Up @@ -55,3 +55,42 @@ func TestModuleEqual_false(t *testing.T) {
})
}
}

func TestModuleString(t *testing.T) {
testCases := map[string]Module{
"": {},
"module.alpha": {
"alpha",
},
"module.alpha.module.beta": {
"alpha",
"beta",
},
"module.alpha.module.beta.module.charlie": {
"alpha",
"beta",
"charlie",
},
}
for str, module := range testCases {
t.Run(str, func(t *testing.T) {
if got, want := module.String(), str; got != want {
t.Errorf("wrong result: got %q, want %q", got, want)
}
})
}
}

func BenchmarkModuleStringShort(b *testing.B) {
module := Module{"a", "b"}
for n := 0; n < b.N; n++ {
module.String()
}
}

func BenchmarkModuleStringLong(b *testing.B) {
module := Module{"southamerica-brazil-region", "user-regional-desktop", "user-name"}
for n := 0; n < b.N; n++ {
module.String()
}
}