Last active
October 21, 2016 06:54
-
-
Save npat-efault/f055654633f43d0ef771d38657fd499e to your computer and use it in GitHub Desktop.
Append consecutive slices, on same underlying array
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 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results: