Skip to content

Instantly share code, notes, and snippets.

@inkel
Created April 12, 2023 22:17
Show Gist options
  • Save inkel/a79f6e27b4b2cc7a4bc3ccdd182dbaa3 to your computer and use it in GitHub Desktop.
Save inkel/a79f6e27b4b2cc7a4bc3ccdd182dbaa3 to your computer and use it in GitHub Desktop.
package main
import (
"strconv"
"testing"
)
func BenchmarkSetSpeed(b *testing.B) {
set := make(map[string]int)
for i := 0; i < 10; i++ {
set[strconv.Itoa(i)] = i
}
b.Run("explicit index", func(b *testing.B) {
for i := 0; i < b.N; i++ {
s := make([]string, len(set))
j := 0
for k := range set {
s[j] = k
j++
}
SS = s
}
})
b.Run("append len=0 cap=len(set)", func(b *testing.B) {
for i := 0; i < b.N; i++ {
s := make([]string, 0, len(set))
for k := range set {
s = append(s, k)
}
SS = s
}
})
b.Run("append len=0 without cap", func(b *testing.B) {
for i := 0; i < b.N; i++ {
var s []string
for k := range set {
s = append(s, k)
}
SS = s
}
})
}
@inkel
Copy link
Author

inkel commented Apr 12, 2023

$ go test -run=XXX -bench=BenchmarkSetSpeed -benchmem -benchtime=10000000x
goos: darwin
goarch: amd64
pkg: github.com/inkel/misc-go-benchmarks
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkSetSpeed/explicit_index-12         	10000000	      177.5 ns/op	    160 B/op	      1 allocs/op
BenchmarkSetSpeed/append_len=0_cap=len(set)-12         	10000000	      180.5 ns/op	    160 B/op	      1 allocs/op
BenchmarkSetSpeed/append_len=0_without_cap-12          	10000000	      427.7 ns/op	    496 B/op	      5 allocs/op
PASS
ok  	github.com/inkel/misc-go-benchmarks	8.371s

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