Skip to content

Instantly share code, notes, and snippets.

@packrat386
Created December 21, 2017 06:20
Show Gist options
  • Save packrat386/edf419d5086da2eb70465cf1dbe5ea43 to your computer and use it in GitHub Desktop.
Save packrat386/edf419d5086da2eb70465cf1dbe5ea43 to your computer and use it in GitHub Desktop.
[fg-386] escape > go test -bench=. -benchmem 2> /dev/null
goos: darwin
goarch: amd64
BenchmarkA-8 2000000000 0.28 ns/op 0 B/op 0 allocs/op
BenchmarkAPrint-8 2000000 682 ns/op 8 B/op 1 allocs/op
BenchmarkEmptyPrint-8 2000000 611 ns/op 0 B/op 0 allocs/op
BenchmarkB-8 2000000000 0.27 ns/op 0 B/op 0 allocs/op
PASS
ok _/Users/acoyle/side/escape 5.117s
[fg-386] escape > go build -gcflags '-m' main.go
# command-line-arguments
./main.go:7:6: can inline A
./main.go:12:6: can inline B
./main.go:25:3: inlining call to A
./main.go:26:3: inlining call to B
./main.go:8:10: A new(int) does not escape
./main.go:13:10: new(int) escapes to heap
./main.go:21:14: *x escapes to heap # <<<<- this is the important bit, when we print it escapes
./main.go:19:10: APrint new(int) does not escape
./main.go:21:13: APrint ... argument does not escape
./main.go:25:3: main new(int) does not escape
./main.go:26:3: main new(int) does not escape
package lolwut
import (
"fmt"
"os"
)
func A() {
x := new(int)
*x = 5
}
func B() *int {
x := new(int)
*x = 5
return x
}
func APrint() {
x := new(int)
*x = 5
fmt.Fprintln(os.Stderr, *x)
}
package lolwut
import (
"fmt"
"os"
"testing"
)
func BenchmarkA(b *testing.B) {
for n := 0; n < b.N; n++ {
A()
}
}
func BenchmarkAPrint(b *testing.B) {
for n := 0; n < b.N; n++ {
APrint()
}
}
func BenchmarkEmptyPrint(b *testing.B) {
for n := 0; n < b.N; n++ {
fmt.Fprintln(os.Stderr, 5)
}
}
func BenchmarkB(b *testing.B) {
for n := 0; n < b.N; n++ {
B()
}
}
package main
import (
"fmt"
)
func A() {
x := new(int)
*x = 5
}
func B() *int {
x := new(int)
*x = 5
return x
}
func APrint() {
x := new(int)
*x = 5
fmt.Println(*x)
}
func main() {
A()
B()
APrint()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment