-
Notifications
You must be signed in to change notification settings - Fork 18.5k
Open
Labels
NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.Someone must examine and confirm this is a valid issue and not a duplicate of an existing one.Performancecompiler/runtimeIssues related to the Go compiler and/or runtime.Issues related to the Go compiler and/or runtime.
Milestone
Description
Consider the following benchmark:
const prefix = "some sufficiently long prefix "
var something = "something"
const suffix = " some sufficiently long suffix"
var sink []byte
func BenchmarkNaive(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
sink = append(sink[:0], prefix+something+suffix...)
}
}There's a number of string concatenations going on, some from variables and others from constants,
which runs in:
BenchmarkNaive-24 23387558 45.20 ns/op 80 B/op 1 allocs/op
However, the benchmark is semantically equivalent to:
func BenchmarkOptimized(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
sink = append(append(append(sink[:0], prefix...), something...), suffix...)
}
}which runs in:
BenchmarkOptimized-24 191343406 6.218 ns/op 0 B/op 0 allocs/op
That is a 100% reduction in allocations, and a dramatic speedup.
The compiler should implicitly perform this transformation for me.
sten4eg, septemhill and CAFxX
Metadata
Metadata
Assignees
Labels
NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.Someone must examine and confirm this is a valid issue and not a duplicate of an existing one.Performancecompiler/runtimeIssues related to the Go compiler and/or runtime.Issues related to the Go compiler and/or runtime.