The following code shows two tests. The first creates a structure by value at each iteration, and the second uses a pointer to the structure.
Why is the last 20 times slower? I know about GC issues with GoLang, but should I not analyze these situations?
I use go1.4beta1, but 1.3.3 gave me [same errors] different results.
Any idea?
package main import "testing" type Adder struct { vals []int } func (a *Adder) add() int { return a.vals[0] + a.vals[1] } func BenchmarkWithoutPointer(b *testing.B) { accum := 0 for i := 0; i < bN; i++ { adder := Adder{[]int{accum, i}} accum = adder.add() } _ = accum } func BenchmarkWithPointer(b *testing.B) { accum := 0 for i := 0; i < bN; i++ { adder := &Adder{[]int{accum, i}} accum = adder.add() } _ = accum }
Benchmark go1.4.1:
$ go test -bench=. testing: warning: no tests to run PASS BenchmarkWithoutPointer 1000000000 2.92 ns/op BenchmarkWithPointer 30000000 57.8 ns/op ok github.com/XXXXXXXXXX/bench/perf 5.010s
Checkpoint go1.3.3:
testing: warning: no tests to run PASS BenchmarkWithoutPointer 500000000 7.89 ns/op BenchmarkWithPointer 50000000 37.5 ns/op ok
EDIT:
Conclusion:
As Ainar-G said, [] int escapes into a heap in the second reference. After reading a little more about 1.4beta1, it seems that new recording options arise when accessing the heap caused by new GC plans. But raw performance seems to have increased. We look forward to 1.5 =).
source share