Skip to content

Commit

Permalink
Merge pull request #31293 from dennygursky/main
Browse files Browse the repository at this point in the history
Performance: string builder speedup for Module.String()
  • Loading branch information
alisdair committed Jun 23, 2022
2 parents 1dcfabd + ad52076 commit a5f307b
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 4 deletions.
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()
}
}

0 comments on commit a5f307b

Please sign in to comment.