by knorker · 12mo ago · 0 comments
Sure, Go has escape analysis, but is that really what's happening here?
Isn't this a better example of escape analysis: https://go.dev/play/p/qX4aWnnwQV2 (the object retains its address, always on the heap, in both caller and callee)
Both arrays in this example seem to be on the heap.
If you want to confirm, you have to use the Go compiler directly. Take the following code:
package main
import (
"fmt"
)
type LogEntry struct {
s string
}
func readLogsFromPartition(partition int) []LogEntry {
var logs []LogEntry // Creating an innocent slice
logs = []LogEntry{{}}
logs2 := []LogEntry{{}}
fmt.Printf("%v %v\n", len(logs), len(logs2))
return []LogEntry{{}}
}
func main() {
logs := readLogsFromPartition(1)
fmt.Printf("%p\n", &logs[0])
}
And compile it with $ go build -gcflags '-m' main.go
# command-line-arguments
./main.go:15:12: inlining call to fmt.Printf
./main.go:21:12: inlining call to fmt.Printf
./main.go:13:19: []LogEntry{...} does not escape
./main.go:14:21: []LogEntry{...} does not escape
./main.go:15:12: ... argument does not escape
./main.go:15:27: len(logs) escapes to heap
./main.go:15:38: len(logs2) escapes to heap
./main.go:16:19: []LogEntry{...} escapes to heap
./main.go:21:12: ... argument does not escape
However, if you return logs2, or if you take the address, or if you pass them to Printf with %v to print them, you'll see that they now escape.An additional note: in your original code from your initial reply, everything you allocate escapes to heap as well. You can confirm in a similar way.
Since 1.17 it’s not impossible for escape analysis to come into play for slices but afaik that is only a consideration for slices with a statically known size under 64KiB.