Running any code for the first time may have some (significant) overhead, for example. related code can be loaded, many things can be delayed until they are needed (for example, internal buffers). Starting the same again can take significantly less time, the difference can even be several orders of magnitude.
Whenever you want to measure the execution time, you have to run it many times, measure the execution time of several runs and calculate the average time. It is also a good idea to exclude the first (some) mileage from the calculation for the above reasons.
Go is the best and easiest way to use test files and control functions. See the doc testing document for more details.
Your case can be compared as follows:
package main import "testing" type abc struct { a, b, c, d int } func BenchmarkSlice(b *testing.B) { a := make([]int, 4) for i := 0; i < bN; i++ { a[0] = 1 a[1] = 2 a[2] = 3 a[3] = 4 } } func BenchmarkStruct(b *testing.B) { a := abc{} for i := 0; i < bN; i++ { aa = 1 ab = 2 ac = 3 ad = 4 } }
Save it in a file like something_test.go , run it with go test -bench . . Output:
BenchmarkSlice-4 2000000000 1.24 ns/op BenchmarkStruct-4 2000000000 0.31 ns/op
You can see that using the structure is about 4 times faster. You will get similar (very close) results if you reorder the reference functions.
source share