This code (playground link):
package main
import (
"fmt"
"testing"
)
var test = make([]int, 0)
func main() {
fmt.Println(testing.Benchmark(testThis))
}
func testThis(b *testing.B) {
fmt.Println(test)
}
has next output:
[]
[]
[]
[]
[]
[]
2000000000 0.00 ns/op
Program exited.
Why there are six []
inside output?
This code (playground link):
package main
import (
"fmt"
)
var test = make([]int, 0)
func main() {
fmt.Println(test)
}
has single output (and it's clear for me):
[]
Program exited.
You are using a benchmark function. This need to execute code multiple times to get a result which is kinda meaningful.
Also your Benchmark is not implemented like the benchmark should be programmed:
The benchmark function must run the target code b.N times. During benchmark execution, b.N is adjusted until the benchmark function lasts long enough to be timed reliably. -- https://golang.org/pkg/testing/
So Benchmark will check the run time and will adjust the b.N to get a good and useful benchmark.
When you just print b.N you get an output like this:
1
100
10000
1000000
100000000
2000000000
2000000000
So in each of the 6 iterations the benchmark is telling you to run a foor loop b.N times.
Sadly you can not use a correct example in the playground because they take to long. But correct would be:
func testThis(b *testing.B) {
for i := 0; i < b.N; i++ {
fmt.Println(test)
}
}