Skip to content

Instantly share code, notes, and snippets.

@richardwu
Last active October 10, 2017 15:41
Show Gist options
  • Select an option

  • Save richardwu/a282758538a39975c3023e0e478db77c to your computer and use it in GitHub Desktop.

Select an option

Save richardwu/a282758538a39975c3023e0e478db77c to your computer and use it in GitHub Desktop.
Golang dynamically-sized slices micro-benchmark
package main
import (
"math/rand"
"testing"
)
const sz = 100
// Percentage of indexes to append.
const pct = 0.9
func Append(input []bool) []int {
var out []int
for i, in := range input {
if in {
out = append(out, i)
}
}
return out
}
func ExactAlloc(input []bool) []int {
count := 0
for _, in := range input {
if in {
count++
}
}
out := make([]int, count)
idx := 0
for i, in := range input {
if in {
out[idx] = i
idx++
}
}
return out
}
func MaxAlloc(input []bool) []int {
out := make([]int, 0, len(input))
for i, in := range input {
if in {
out = append(out, i)
}
}
return out
}
var result []int
func randBoolSlice() []bool {
out := make([]bool, sz)
for i := range out {
out[i] = rand.Float64() < pct
}
return out
}
func BenchmarkAppend(b *testing.B) {
var res []int
for i := 0; i < b.N; i++ {
in := randBoolSlice()
res = Append(in)
}
result = res
}
func BenchmarkExactAlloc(b *testing.B) {
var res []int
for i := 0; i < b.N; i++ {
in := randBoolSlice()
res = ExactAlloc(in)
}
result = res
}
func BenchmarkMaxAlloc(b *testing.B) {
var res []int
for i := 0; i < b.N; i++ {
in := randBoolSlice()
res = MaxAlloc(in)
}
result = res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment