Skip to content

Instantly share code, notes, and snippets.

@jameinel
Created February 11, 2022 15:47
Show Gist options
  • Save jameinel/22fc619d8b69459c1be83481180d2a71 to your computer and use it in GitHub Desktop.
Save jameinel/22fc619d8b69459c1be83481180d2a71 to your computer and use it in GitHub Desktop.
Benchmark copy vs append
package foo
import "testing"
func createSource(b *testing.B) []int {
source := make([]int, b.N)
for i := range source {
source[i] = i
}
b.ResetTimer()
return source
}
func BenchmarkCopyN(b *testing.B) {
source := createSource(b)
dest := make([]int, len(source))
copy(dest, source)
}
func BenchmarkAppendN(b *testing.B) {
source := createSource(b)
dest := append([]int(nil), source...)
_ = dest
}
func BenchmarkAppendSourceN(b *testing.B) {
source := createSource(b)
dest := append(source[:0], source...)
_ = dest
}
func createN(b *testing.B, n int) []int {
source := make([]int, n)
for i := range source {
source[i] = i
}
b.ResetTimer()
return source
}
func BenchmarkCopy1000(b *testing.B) {
source := createN(b, 1000)
for i := 0; i < b.N; i++ {
dest := make([]int, len(source))
copy(dest, source)
_ = dest
}
}
func BenchmarkAppend1000(b *testing.B) {
source := createN(b, 1000)
for i := 0; i < b.N; i++ {
dest := append([]int(nil), source...)
_ = dest
}
}
func BenchmarkAppendSource1000(b *testing.B) {
source := createN(b, 1000)
for i := 0; i < b.N; i++ {
dest := append(source[:0], source...)
_ = dest
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment