You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
package alloc_test
import"testing"vars="some string to be doubled by foo"funcfoo() string {
buf:=make([]byte, len(s)*2)
copy(buf, s)
copy(buf[:len(s)], s)
returnstring(buf)
}
funcBenchmarkGarbage(b*testing.B) {
b.ReportAllocs()
fori:=0; i<b.N; i++ {
foo()
}
}
The string(buf) conversion allocates memory, even though the buf variable should not escape, and is only used by string(buf) at the exit of the function.
Reusing the storage of the byte slice in string([]byte) should be doable.
The escape analysis pass already provides the escape info we need, I believe.
The additional check would be to make sure that the []byte is not modified after the string cast by the function being compiled. I'm not sure what mechanism we'd need for that. Maybe just an imminent return after the cast would catch most cases we want.
In a program like:
The
string(buf)
conversion allocates memory, even though thebuf
variable should not escape, and is only used by string(buf) at the exit of the function.This results in two allocations per call to
foo
:More practically, this affects things like
filepath.Join
orpath.Join
which usesstrings.Join
(which looks likefoo
above)I thought we had this bug open already but I can't find it.
/cc @randall77 @josharian
The text was updated successfully, but these errors were encountered: