简单计算基准的基本解释

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

It gets optimized away. If you do something with x after the loop, you'll find they all perform about the same:

var buf = new(bytes.Buffer)

func add1(i int) int {
    return i + 1
}

func BenchmarkAdd1(b *testing.B) {
    var x = 0
    for i := 0; i < b.N; i++ {
        x = x + 1
    }
    fmt.Fprintln(buf, x)
}

func BenchmarkAdd1ForceType(b *testing.B) {
    var x = 0
    for i := 0; i < b.N; i++ {
        x = x + int(1)
    }
    fmt.Fprintln(buf, x)
}

func BenchmarkIncrement(b *testing.B) {
    var x = 0
    for i := 0; i < b.N; i++ {
        x++
    }
    fmt.Fprintln(buf, x)
}

func BenchmarkAdd1WithFunction(b *testing.B) {
    var x = 0
    for i := 0; i < b.N; i++ {
        x = add1(x)
    }
    fmt.Fprintln(buf, x)
}

This yields:

BenchmarkAdd1-4                 2000000000           0.34 ns/op
BenchmarkAdd1ForceType-4        2000000000           0.33 ns/op
BenchmarkIncrement-4            2000000000           0.34 ns/op
BenchmarkAdd1WithFunction-4     2000000000           0.35 ns/op