Last active
February 3, 2022 23:00
-
-
Save mikeschinkel/fbeb291b90970581b4428fbc14e4ab19 to your computer and use it in GitHub Desktop.
GoLang benchmark for aggregating of multiple slice elements into a single slice
This file contains 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 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 | |
} |
This file contains 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
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