Skip to content

Instantly share code, notes, and snippets.

@npat-efault
Last active October 21, 2016 06:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npat-efault/f055654633f43d0ef771d38657fd499e to your computer and use it in GitHub Desktop.
Save npat-efault/f055654633f43d0ef771d38657fd499e to your computer and use it in GitHub Desktop.
Append consecutive slices, on same underlying array
package tstappend
import "testing"
const N = 8192
func appendBytes(a, b []byte) []byte {
if len(b) == 0 {
return a
}
if cap(a) >= len(a)+len(b) && &a[:len(a)+1][len(a)] == &b[0] {
return a[:len(a)+len(b)]
}
return append(a, b...)
}
func BenchmarkAppendBytes(b *testing.B) {
bf := make([]byte, N)
bf0 := bf[0:0]
b.ResetTimer()
var bf1 []byte
for i := 0; i < b.N; i++ {
bf1 = appendBytes(bf0, bf)
}
bf0 = bf1
}
func BenchmarkAppend(b *testing.B) {
bf := make([]byte, N)
bf0 := make([]byte, 0, N)
var bf1 []byte
b.ResetTimer()
for i := 0; i < b.N; i++ {
bf1 = append(bf0, bf...)
}
bf0 = bf1
}
func BenchmarkCopy(b *testing.B) {
bf := make([]byte, N)
bf0 := make([]byte, N)
b.ResetTimer()
for i := 0; i < b.N; i++ {
copy(bf0, bf)
}
}
@npat-efault
Copy link
Author

npat-efault commented Oct 16, 2016

Results:

go test -bench=.
testing: warning: no tests to run
BenchmarkAppendBytes-4      2000000000           0.32 ns/op
BenchmarkAppend-4            3000000           415 ns/op
BenchmarkCopy-4              3000000           424 ns/op
PASS
ok      github.com/npat-efault/tst/tstappend    4.128s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment