Created
October 31, 2020 09:59
-
-
Save romanitalian/a4e979ef0fe397803221e13ea52ac88a to your computer and use it in GitHub Desktop.
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 ( | |
"testing" | |
) | |
type box struct { | |
data *byte | |
} | |
// 11.2 ns/op | |
func dumberFieldInHeap() { | |
b := new(box) | |
b.data = new(byte) // b.data escapes to heap (conservative way) | |
} | |
// 0.287 ns/op | |
func dumber1() { | |
b := &box{data: new(byte)} // escape analysis detect work on stack (no heap) | |
_ = b | |
} | |
// 0.285 ns/op | |
func dumber2() { | |
var b box | |
b.data = new(byte) // // escape analysis detect work on stack (no heap) | |
} | |
// 2.261e-06 sec | |
func BenchmarkEscapeStructAndPointerField(b *testing.B) { | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
dumberFieldInHeap() | |
} | |
} | |
// 1.43e-07 | |
func BenchmarkEscapeStructAndPointerField_NoEscapes_1(b *testing.B) { | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
dumber1() | |
} | |
} | |
// 1.69e-07 | |
func BenchmarkEscapeStructAndPointerField_NoEscapes_2(b *testing.B) { | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
dumber2() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment