Skip to content

Instantly share code, notes, and snippets.

@x1unix
Created February 20, 2024 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save x1unix/1c2b6b89360ec148393b80fe10e83696 to your computer and use it in GitHub Desktop.
Save x1unix/1c2b6b89360ec148393b80fe10e83696 to your computer and use it in GitHub Desktop.
[GO] Append vs Copy
package main
import (
"fmt"
"runtime"
"testing"
)
func BenchmarkAppend(b *testing.B) {
for i := 0; i < b.N; i++ {
i1 := []int{1, 2, 3}
i2 := []int{4, 5, 6}
o := make([]int, 0, len(i1)+len(i2))
o = append(o, i1...)
o = append(o, i2...)
}
b.ReportAllocs()
}
func BenchmarkCopy(b *testing.B) {
for i := 0; i < b.N; i++ {
i1 := []int{1, 2, 3}
i2 := []int{4, 5, 6}
o := make([]int, len(i1)+len(i2))
copy(o, i1)
copy(o[:len(i1)], i2)
}
b.ReportAllocs()
}
func main() {
bench("copy", BenchmarkCopy)
bench("append", BenchmarkAppend)
}
func bench(label string, fn func(b *testing.B)) {
fmt.Printf("=== Running %q ===\n", label)
var (
startAllocs runtime.MemStats
endAllocs runtime.MemStats
)
runtime.ReadMemStats(&startAllocs)
res := testing.Benchmark(fn)
fmt.Println(res)
runtime.ReadMemStats(&endAllocs)
fmt.Printf("> Allocs: %d\n", endAllocs.Mallocs-startAllocs.Mallocs)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment