-
-
Save extemporalgenome/4532825 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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