Skip to content

Instantly share code, notes, and snippets.

@kwilczynski
Created August 21, 2023 04:15
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 kwilczynski/f2be077bafaea3aa1ae024020c0962c5 to your computer and use it in GitHub Desktop.
Save kwilczynski/f2be077bafaea3aa1ae024020c0962c5 to your computer and use it in GitHub Desktop.
package main
import (
"testing"
)
func A() {
m := map[int][]string{}
for i, _ := range []int{1, 2, 3} {
var x []string
for _, c := range []string{"a", "b", "c"} {
x = append(x, c)
}
m[i] = x
}
}
func B() {
m := map[int][]string{}
var x []string
for i, _ := range []int{1, 2, 3} {
for _, c := range []string{"a", "b", "c"} {
x = append(x, c)
}
m[i] = x
x = nil
}
}
func BenchmarkA(b *testing.B) {
for i := 0; i < b.N; i++ {
A()
}
}
func BenchmarkB(b *testing.B) {
for i := 0; i < b.N; i++ {
B()
}
}
@kwilczynski
Copy link
Author

For me, on 64-bit Linux, "A" tends to run slightly faster (not that there is any real-life difference here), most of the time (note: this does not mean always).

$ go test -bench=. -benchmem 
goos: linux
goarch: amd64
pkg: test
cpu: AMD Ryzen 9 6900HX with Radeon Graphics        
BenchmarkA-16    	 1637730	       763.1 ns/op	     336 B/op	       9 allocs/op
BenchmarkB-16    	 1480376	       789.4 ns/op	     336 B/op	       9 allocs/op
PASS
ok  	test	3.981s

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