I wrote the following Go benchmarks (Go1.9.2, Linux amd64) to test indexing vs appending:
func BenchmarkIndex(b *testing.B) {
for i := 0; i < b.N; i++ {
existing := make([]int64, 1000, 1000)
init := make([]int64, 1000) // len 1000, cap 1000
for index, element := range existing {
init[index] = element
}
}
}
func BenchmarkAppend(b *testing.B) {
for i := 0; i < b.N; i++ {
existing := make([]int64, 1000, 1000)
init := make([]int64, 0, 1000) // len 0, capacity 1000
for _, element := range existing {
init = append(init, element)
}
}
}
And got the following results:
goos: linux
goarch: amd64
BenchmarkIndex-4 1000000 2183 ns/op
BenchmarkAppend-4 1000000 1933 ns/op
PASS
I'm a little confused on why append seems to perform better than in general than indexing into the slice. Does it have anything to do with omitting the index inside the range? If not, what is append doing under the hood to make it quicker than just indexing?
For reference, here is append's source. Thanks!