The following benchmarks performs best on the one with a function operating the calculation. Even if it inlines, why does it perform better?
func add1(i int) int {
return i + 1
}
var x = 0
func BenchmarkAdd1(b *testing.B) {
for i := 0; i < b.N; i++ {
x = x + 1
}
}
func BenchmarkAdd1ForceType(b *testing.B) {
for i := 0; i < b.N; i++ {
x = x + int(1)
}
}
func BenchmarkIncrement(b *testing.B) {
for i := 0; i < b.N; i++ {
x++
}
}
func BenchmarkAdd1WithFunction(b *testing.B) {
for i := 0; i < b.N; i++ {
x = add1(x)
}
}
BenchmarkAdd1-8 1000000000 1.99 ns/op
BenchmarkAdd1ForceType-8 2000000000 1.96 ns/op
BenchmarkIncrement-8 2000000000 2.02 ns/op
BenchmarkAdd1WithFunction-8 2000000000 0.44 ns/op
CPU is Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz
Go version 1.9.2 darwin/amd64