Skip to content

Instantly share code, notes, and snippets.

@xogeny
Created January 27, 2015 18:04
Show Gist options
  • Save xogeny/b819af6a0cf8ba1caaef to your computer and use it in GitHub Desktop.
Save xogeny/b819af6a0cf8ba1caaef to your computer and use it in GitHub Desktop.
Benchmark for append vs. copy in Golang
package copy_vs_append
import (
"testing"
)
func TestCopy(t *testing.T) {
y := doCopy(true, false)
if len(y) != 1000 {
t.Fatalf("Expected len(y) to be 1000 but was %d", len(y))
}
}
func TestAppend(t *testing.T) {
y := doCopy(false, false)
if len(y) != 1000 {
t.Fatalf("Expected len(y) to be 1000 but was %d", len(y))
}
}
func TestAppendAlloc(t *testing.T) {
y := doCopy(false, true)
if len(y) != 1000 {
t.Fatalf("Expected len(y) to be 1000 but was %d", len(y))
}
}
func doCopy(useCopy bool, preAlloc bool) []int64 {
existing := make([]int64, 1000, 1000)
var y []int64
if useCopy {
y = make([]int64, 1000, 1000)
copy(y, existing)
} else {
var init []int64
if preAlloc {
init = make([]int64, 0, 1000)
} else {
init = []int64{}
}
y = append(init, existing...)
}
return y
}
func BenchmarkAppend(b *testing.B) {
for i := 0; i < b.N; i++ {
doCopy(false, false)
}
}
func BenchmarkAppendAlloc(b *testing.B) {
for i := 0; i < b.N; i++ {
doCopy(false, true)
}
}
func BenchmarkAppendAllocInline(b *testing.B) {
for i := 0; i < b.N; i++ {
existing := make([]int64, 1000, 1000)
var init []int64
init = make([]int64, 0, 1000)
_ = append(init, existing...)
}
}
func BenchmarkCopy(b *testing.B) {
for i := 0; i < b.N; i++ {
doCopy(true, true)
}
}
@smyrman
Copy link

smyrman commented Aug 27, 2020

Did some modification to the benchmark to meassure inline copy v.s. inline append for the pre-allocated case only (not counting the allocation cost of the 'existing' data to copy).

https://gist.github.com/smyrman/f7fd1734f9ea20d4648ed359bbcc6ac7

i believe this may be more relevant to compare. The benchmark code here include a number of branches (if statements), which in themselves may be expensive (if predicted wrong), or at least expensive enough to affect the results.

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