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
Benchmarked (a function that calls) strings.Join and looked at the memory allocations with pprof. (With go test -bench Join -benchmem -memprofile mem.pprof -memprofilerate 1 -run ^$)
Memory profile for strings.Join (go tool pprof --alloc_objects <binary> mem.pprof):
1204055 1204055 (flat, cum) 100% of Total
. . 358: n := len(sep) * (len(a) - 1)
. . 359: for i := 0; i < len(a); i++ {
. . 360: n += len(a[i])
. . 361: }
. . 362:
602028 602028 363: b := make([]byte, n)
. . 364: bp := copy(b, a[0])
. . 365: for _, s := range a[1:] {
. . 366: bp += copy(b[bp:], sep)
. . 367: bp += copy(b[bp:], s)
. . 368: }
602027 602027 369: return string(b)
. . 370:}
What did you expect to see?
The compiler reusing the memory of b for the return value.
What did you see instead?
The []byte->string conversion in strings.Join (on line 369) allocates a new string, although the []byte could be reused as there can never be a reference to the []byte after the function returns and the []byte is already on the heap¹.
¹ Calling 'go build -gcflags="-m" in the strings package confirms this:
./strings.go:363: make([]byte, n) escapes to heap
./strings.go:369: string(b) escapes to heap
(Line numbers are from tip)
The text was updated successfully, but these errors were encountered:
go version
)?go version go1.6 linux/amd64
and
go version devel +ea4b785 Tue Mar 15 08:43:34 2016 +0000 linux/amd64
go env
)?Benchmarked (a function that calls) strings.Join and looked at the memory allocations with pprof. (With
go test -bench Join -benchmem -memprofile mem.pprof -memprofilerate 1 -run ^$
)Benchmarks for strings.Join: http://play.golang.org/p/R7snLsnFmg
Benchmark results:
Memory profile for strings.Join (
go tool pprof --alloc_objects <binary> mem.pprof
):The compiler reusing the memory of b for the return value.
The []byte->string conversion in strings.Join (on line 369) allocates a new string, although the []byte could be reused as there can never be a reference to the []byte after the function returns and the []byte is already on the heap¹.
¹ Calling 'go build -gcflags="-m" in the strings package confirms this:
(Line numbers are from tip)
The text was updated successfully, but these errors were encountered: