Skip to content

Instantly share code, notes, and snippets.

@YanhaoYang
Created June 27, 2017 09:38
Show Gist options
  • Save YanhaoYang/24e93dc2d8bbabc6f6136e32c5677d3a to your computer and use it in GitHub Desktop.
Save YanhaoYang/24e93dc2d8bbabc6f6136e32c5677d3a to your computer and use it in GitHub Desktop.
[Golang] make a slice and populate it by index or with `append`?
package main
import (
"fmt"
"testing"
)
func BenchmarkAppendFloat(b *testing.B) {
benchmarks := []int{10, 100, 1000, 10000, 1e5}
for _, bm := range benchmarks {
b.Run(fmt.Sprintf("%d index", bm), func(b *testing.B) {
for i := 0; i < b.N; i++ {
s := make([]int, bm)
for i := 0; i < bm; i++ {
s[i] = i
}
}
})
b.Run(fmt.Sprintf("%d append", bm), func(b *testing.B) {
for i := 0; i < b.N; i++ {
s := make([]int, bm)
for i := 0; i < bm; i++ {
s = append(s, i)
}
}
})
}
}
//> go test -bench=. 1
//BenchmarkAppendFloat/10_index-4 30000000 57.5 ns/op
//BenchmarkAppendFloat/10_append-4 10000000 166 ns/op
//BenchmarkAppendFloat/100_index-4 5000000 334 ns/op
//BenchmarkAppendFloat/100_append-4 2000000 892 ns/op
//BenchmarkAppendFloat/1000_index-4 500000 2675 ns/op
//BenchmarkAppendFloat/1000_append-4 200000 7280 ns/op
//BenchmarkAppendFloat/10000_index-4 100000 21121 ns/op
//BenchmarkAppendFloat/10000_append-4 10000 109381 ns/op
//BenchmarkAppendFloat/100000_index-4 5000 203999 ns/op
//BenchmarkAppendFloat/100000_append-4 1000 1456461 ns/op
//PASS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment