To make slice append operation faster we need to allocate enough capacity. There\'s two ways to append slice, Here is the code:
func BenchmarkSliceAppend(b *t
It seems like some improvements of Go compiler or runtime have been introduced since this question has been posted, so now (Go 1.10.1
) there is no significant difference between append
and direct assignment by index.
Also, I had to change your benchmarks slightly because of OOM panics.
package main
import "testing"
var result []int
const size = 32
const iterations = 100 * 1000 * 1000
func doAssign() {
data := make([]int, size)
for i := 0; i < size; i++ {
data[i] = i
}
result = data
}
func doAppend() {
data := make([]int, 0, size)
for i := 0; i < size; i++ {
data = append(data, i)
}
result = data
}
func BenchmarkAssign(b *testing.B) {
b.N = iterations
for i := 0; i < b.N; i++ {
doAssign()
}
}
func BenchmarkAppend(b *testing.B) {
b.N = iterations
for i := 0; i < b.N; i++ {
doAppend()
}
}
Results:
➜ bench_slice_assign go test -bench=Bench .
goos: linux
goarch: amd64
BenchmarkAssign-4 100000000 80.9 ns/op
BenchmarkAppend-4 100000000 81.9 ns/op
PASS
ok _/home/isaev/troubles/bench_slice_assign 16.288s