string builder speed up for Module.String()

pull/31293/head
Denny Gursky 4 years ago
parent fd45fb969c
commit 8a694e81ff

@ -33,11 +33,21 @@ func (m Module) String() string {
if len(m) == 0 {
return ""
}
var steps []string
size := 0
for _, s := range m {
steps = append(steps, "module", s)
size += len(s)
}
return strings.Join(steps, ".")
var sb strings.Builder
// 8 is len("module.") + len(".")
sb.Grow(8*len(m) + size)
for i, s := range m {
sb.WriteString("module.")
sb.WriteString(s)
if i != len(m)-1 {
sb.WriteString(".")
}
}
return sb.String()
}
func (m Module) Equal(other Module) bool {

@ -55,3 +55,17 @@ func TestModuleEqual_false(t *testing.T) {
})
}
}
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