|
|
|
|
|
by weberc2
2882 days ago
|
|
Looks like you're right about interfaces (full benchmark source code: https://gist.github.com/weberc2/87d2fdc379065a2765d1c9f490ad...)! BenchmarkEscapeInterface-4 50000000 33.3 ns/op 8 B/op 1 allocs/op
BenchmarkEscapeConcreteValue-4 200000000 9.45 ns/op 0 B/op 0 allocs/op
BenchmarkEscapeConcretePointer-4 100000000 10.0 ns/op 0 B/op 0 allocs/op
But arrays are stack allocated: BenchmarkEscapeArray-4 50000000 21.3 ns/op 0 B/op 0 allocs/op
And structs are stack allocated, as are their fields--even fields that are structs, slices, and strings!: BenchmarkEscapeStruct-4 100000000 12.8 ns/op 0 B/op 0 allocs/op
The code: 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()
}
}
|
|