Created
July 31, 2018 15:41
-
-
Save weberc2/87d2fdc379065a2765d1c9f490ad8f9e to your computer and use it in GitHub Desktop.
Exploring escape analysis in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strconv" | |
"testing" | |
) | |
type Int int | |
func (i Int) String() string { | |
return strconv.Itoa(int(i)) | |
} | |
type Int2 int | |
func (i *Int2) String() string { | |
return strconv.Itoa(int(*i)) | |
} | |
func BenchmarkEscapeInterface(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
var i Int = 10 | |
var s fmt.Stringer = i | |
s.String() | |
} | |
} | |
func BenchmarkEscapeConcreteValue(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
var i Int = 10 | |
i.String() | |
} | |
} | |
func BenchmarkEscapeConcretePointer(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
var i Int2 = 10 | |
i.String() | |
} | |
} | |
func sum() int { | |
var ints [10]int | |
for i := 0; i < len(ints); i++ { | |
ints[0] = i + 1 | |
} | |
sum := 0 | |
for _, x := range ints { | |
sum += x | |
} | |
return sum | |
} | |
func BenchmarkEscapeArray(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
_ = sum() | |
} | |
} | |
type Inner struct { | |
Slice []int | |
String string | |
Int int | |
} | |
type Struct struct { | |
Int int | |
String string | |
Nested Inner | |
} | |
func (s Struct) AddThings() int { | |
return s.Int + len(s.String) + len(s.Nested.Slice) + len(s.Nested.String) + | |
s.Nested.Int | |
} | |
func BenchmarkEscapeStruct(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
s := Struct{ | |
Int: 42, | |
String: "Hello", | |
Nested: Inner{ | |
Slice: []int{0, 1, 2}, | |
String: "World!", | |
Int: 42, | |
}, | |
} | |
_ = s.AddThings() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment