That tells me that the compiler realizes that the result of make([]byte, 1024) doesn't escape. My question was, what does it do with this information? Does it the byte slice's backing array to be allocated on the stack instead of the heap?
After looking at the generated assembly for a few different variations of a function like this, I've realized that the compiler DOES make this optimization already. But the -m flag only tells us that the compiler will consider the optimization. The decision to allocate it on the stack or heap seems to depend on the buffer size.
In particular, for a function like f above, a buffer size of 1024 compiled into something like f2 above. But when I changed 1024 to 65536, it actually called makeslice to put it on the heap.
On Wednesday, February 12, 2014 2:11:13 PM UTC-5, andrey mirtchovski wrote:you can check for yourself:
$ cat t.go
package test
func f() int {
buf := make([]byte, 1024)
return len(buf)
}
$ go build -gcflags=-m t.go
# command-line-arguments
./t.go:3: can inline f
./t.go:4: f make([]byte, 1024) does not escape
$
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
Yes. As stack frames are taken from the heap anyway, if the local allocation would cause a stack split, and thus an allocation on the heap anyway, the compiler takes the lesser of evils and allocates your large buffer on the heap in an effort to avoid a stack split.
No. Generally the runtime doesn't explicitly free memory now. (e.g. it will only be freed until the next GC).
Yes. As stack frames are taken from the heap anyway, if the local allocation would cause a stack split, and thus an allocation on the heap anyway, the compiler takes the lesser of evils and allocates your large buffer on the heap in an effort to avoid a stack split.