Merge pull request #31293 from dennygursky/main

Performance: string builder speedup for Module.String()
pull/31310/head
Alisdair McDiarmid 4 years ago committed by GitHub
commit a5f307b5e4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -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 {

@ -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()
}
}

Loading…
Cancel
Save