Last active
October 10, 2017 15:41
-
-
Save richardwu/a282758538a39975c3023e0e478db77c to your computer and use it in GitHub Desktop.
Golang dynamically-sized slices micro-benchmark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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