Skip to content

Instantly share code, notes, and snippets.

@extemporalgenome
Forked from donovanhide/Benchmark
Last active December 11, 2015 02:48
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 extemporalgenome/4532825 to your computer and use it in GitHub Desktop.
Save extemporalgenome/4532825 to your computer and use it in GitHub Desktop.
For whatever reason, at least with amd64 tests builds on my AMD X2 3800+,
the pointer receiver implementation is 13% slower when bound checks are elided.
# default run (value receiver is 49% slower than ptr receiver)
go test -bench .
BenchmarkSortVal 1000000 1300 ns/op
BenchmarkSortPtrToVal 1000000 1297 ns/op
BenchmarkSortPtr 2000000 870 ns/op
# no bounds checking (value receiver is 11% slower than ptr receiver)
go test -gcflags '-B' -bench .
BenchmarkSortVal 1000000 1106 ns/op
BenchmarkSortPtrToVal 1000000 1105 ns/op
BenchmarkSortPtr 2000000 990 ns/op
# no optimizations (value receiver is 13% slower than ptr receiver)
go test -gcflags '-N' -bench .
BenchmarkSortVal 1000000 1552 ns/op
BenchmarkSortPtrToVal 1000000 1558 ns/op
BenchmarkSortPtr 1000000 1368 ns/op
package main
import (
"math/rand"
"sort"
"testing"
)
type Inverted struct {
Hash uint32
Position int
}
type InvertedSlice []Inverted
func (s InvertedSlice) Len() int { return len(s) }
func (s InvertedSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s InvertedSlice) Less(i, j int) bool {
return s[i].Hash < s[j].Hash || s[i].Hash == s[j].Hash && s[i].Position < s[j].Position
}
type InvertedSlicePtr []Inverted
func (s *InvertedSlicePtr) Len() int { return len(*s) }
func (s *InvertedSlicePtr) Swap(i, j int) { (*s)[i], (*s)[j] = (*s)[j], (*s)[i] }
func (s *InvertedSlicePtr) Less(i, j int) bool {
return (*s)[i].Hash < (*s)[j].Hash || (*s)[i].Hash == (*s)[j].Hash && (*s)[i].Position < (*s)[j].Position
}
func BenchmarkSortVal(b *testing.B) {
rand.Seed(12345)
s := make(InvertedSlice, b.N)
for i := range s {
s[i] = Inverted{rand.Uint32(), b.N - i}
}
b.ResetTimer()
sort.Sort(s)
}
func BenchmarkSortPtrToVal(b *testing.B) {
rand.Seed(12345)
s := make(InvertedSlice, b.N)
for i := range s {
s[i] = Inverted{rand.Uint32(), b.N - i}
}
b.ResetTimer()
sort.Sort(&s)
}
func BenchmarkSortPtr(b *testing.B) {
rand.Seed(12345)
s := make(InvertedSlicePtr, b.N)
for i := range s {
s[i] = Inverted{rand.Uint32(), b.N - i}
}
b.ResetTimer()
sort.Sort(&s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment