Skip to content

Instantly share code, notes, and snippets.

@totoleo
Last active June 29, 2020 13:36
Show Gist options
  • Save totoleo/d9ce87cd8affe805df7f4d6da8cb2fa9 to your computer and use it in GitHub Desktop.
Save totoleo/d9ce87cd8affe805df7f4d6da8cb2fa9 to your computer and use it in GitHub Desktop.
slice chunk
goos: darwin
goarch: amd64
pkg: perf
BenchmarkBulk
BenchmarkBulk/re
BenchmarkBulk/re-4 15252195 67.9 ns/op 48 B/op 1 allocs/op
BenchmarkBulk/slow
BenchmarkBulk/slow-4 224365 5269 ns/op 12352 B/op 29 allocs/op
PASS
package main
import "testing"
func BenchmarkBulk(b *testing.B) {
const bulk = 50
const max = 1400
var ids = make([]int, max)
for i, _ := range ids {
ids[i] = i
}
b.Run("re", func(b *testing.B) {
var dup = make([]int, max)
copy(dup, ids)
b.ReportAllocs()
for i := 0; i < b.N; i++ {
var chunks = make([][]int, 0, len(dup)/bulk+1)
for bulk < len(dup) {
chunks, dup = append(chunks, dup[:bulk]), dup[bulk:]
}
chunks = append(chunks, dup)
}
})
b.Run("slow", func(b *testing.B) {
var dup = make([]int, max)
copy(dup, ids)
b.ReportAllocs()
for i := 0; i < b.N; i++ {
var chunks = make([][]int, 0, len(dup)/bulk+1)
var slice []int = make([]int, 0, bulk)
var i int
for _, id := range dup {
if i < bulk {
slice = append(slice, id)
i++
} else {
chunks = append(chunks, slice)
slice = make([]int, 0, bulk)
slice = append(slice, id)
i = 1
}
}
chunks = append(chunks, slice)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment