The issue
Go tip doesn't know that string / []byte arguments passed to functions like strings.IndexByte don't escape. This leads to unnecessary allocation and copy in the following code:
package stringsIndex_test
import (
"strings"
"testing"
)
func BenchmarkStringsIndexByte(b *testing.B) {
bb := []byte("foobar baz")
b.ReportAllocs()
for i := 0; i < b.N; i++ {
// string(bb) unnecessarily allocates new string and copies bb contents to it.
n := strings.IndexByte(string(bb), ' ')
Sink += n
}
}
var Sink int
Benchmark results indicate an unnecessary allocation:
BenchmarkStringsIndexByte 50000000 30.5 ns/op 16 B/op 1 allocs/op
The solution
Mark strings and bytes functions accepting string / []byte as go:noescape in order to eliminate unnecessary allocations in the code above.
The issue
Go tip doesn't know that
string/[]bytearguments passed to functions likestrings.IndexBytedon't escape. This leads to unnecessary allocation and copy in the following code:Benchmark results indicate an unnecessary allocation:
The solution
Mark
stringsandbytesfunctions acceptingstring/[]byteasgo:noescapein order to eliminate unnecessary allocations in the code above.