Golang全局变量访问在基准测试中很慢

Here is a simple golang benchmark test, it runs x++ in three different ways:

  1. in a simple for loop with x declared inside function
  2. in a nested loop with x declared inside function
  3. in a nested loop with x declared as global variable
package main

import (
    "testing"
)

var x = 0

func BenchmarkLoop(b *testing.B) {
    x := 0
    for n := 0; n < b.N; n++ {
        x++
    }
}

func BenchmarkDoubleLoop(b *testing.B) {
    x := 0
    for n := 0; n < b.N/1000; n++ {
        for m := 0; m < 1000; m++ {
            x++
        }
    }
}

func BenchmarkDoubleLoopGlobalVariable(b *testing.B) {
    for n := 0; n < b.N/1000; n++ {
        for m := 0; m < 1000; m++ {
            x++
        }
    }
}

And the result is as following:

$ go test -bench=.

BenchmarkLoop-8                         2000000000               0.32 ns/op
BenchmarkDoubleLoop-8                   2000000000               0.34 ns/op
BenchmarkDoubleLoopGlobalVariable-8     2000000000               2.00 ns/op
PASS
ok      github.com/cizixs/playground/loop-perf  5.597s

Obviously, the first and second methods have similar performance, while the third function is much slower(about 6x times slow).

And I wonder why this is happening, is there a way to improve performance of global variable access?

I wonder why this is happening.

The compiler optimizes away your whole code. 300ps per op means a only a noop was "executed".