Skip to content

Instantly share code, notes, and snippets.

@mikeschinkel
Last active February 3, 2022 23:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeschinkel/fbeb291b90970581b4428fbc14e4ab19 to your computer and use it in GitHub Desktop.
Save mikeschinkel/fbeb291b90970581b4428fbc14e4ab19 to your computer and use it in GitHub Desktop.
GoLang benchmark for aggregating of multiple slice elements into a single slice
package test
//
// Initial source for benchmark from https://stackoverflow.com/a/40678026/102699
// Added BenchmarkConcatAppendPreAllocate()
//
import "testing"
func BenchmarkConcatCopyPreAllocate(b *testing.B) {
for n := 0; n < b.N; n++ {
B = concatCopyPreAllocate(slices)
}
}
func BenchmarkConcatAppendPreAllocate(b *testing.B) {
for n := 0; n < b.N; n++ {
B = concatAppendPreAllocate(slices)
}
}
func BenchmarkConcatAppend(b *testing.B) {
for n := 0; n < b.N; n++ {
B = concatAppend(slices)
}
}
var slices = [][]byte{
[]byte("my first slice"),
[]byte("second slice"),
[]byte("third slice"),
[]byte("fourth slice"),
[]byte("fifth slice"),
}
var B []byte
func concatAppendPreAllocate(slices [][]byte) []byte {
var totalLen int
for _, s := range slices {
totalLen += len(s)
}
tmp := make([]byte, 0, totalLen)
for _, s := range slices {
tmp = append(tmp,s...)
}
return tmp
}
func concatCopyPreAllocate(slices [][]byte) []byte {
var totalLen int
for _, s := range slices {
totalLen += len(s)
}
tmp := make([]byte, totalLen)
var i int
for _, s := range slices {
i += copy(tmp[i:], s)
}
return tmp
}
func concatAppend(slices [][]byte) []byte {
var tmp []byte
for _, s := range slices {
tmp = append(tmp, s...)
}
return tmp
}
goos: darwin
goarch: amd64
cpu: Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz
BenchmarkConcatCopyPreAllocate
BenchmarkConcatCopyPreAllocate-8 19351508 62.89 ns/op
BenchmarkConcatAppendPreAllocate
BenchmarkConcatAppendPreAllocate-8 20998980 57.53 ns/op
BenchmarkConcatAppend
BenchmarkConcatAppend-8 8931429 132.0 ns/op
PASS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment