1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
package main
import (
"sort"
"testing"
)
type User struct {
Name string
Age int
}
var TestCases = []User{
{"alice", 9},
{"james", 35},
{"wade", 15},
{"test", 51},
{"beyond", 25},
{"brand", 59},
{"bob", 10},
{"twitter", 15},
{"google", 22},
{"facebook", 91},
}
// Example One - Sorting Slice Directly
// somehow - slowest way to sort it.
func SortSlice(users []User) {
sort.Slice(users, func(i, j int) bool {
return users[i].Name < users[j].Name
})
}
func BenchmarkSlice(b *testing.B) {
tmp := make([]User, len(TestCases))
for i := 0; i < b.N; i++ {
copy(tmp, TestCases)
SortSlice(tmp)
}
}
// Example Two - Sorting Slice Directly
// much faster performance
type ByName []User
// Sort interface implementation
func (n ByName) Less(i, j int) bool { return n[i].Name < n[j].Name }
func (n ByName) Len() int { return len(n) }
func (n ByName) Swap(i, j int) { n[i], n[j] = n[j], n[i] }
func SortStruct(users []User) {
sort.Sort(ByName(users))
}
func BenchmarkStruct(b *testing.B) {
tmp := make([]User, len(TestCases))
for i := 0; i < b.N; i++ {
copy(tmp, TestCases)
SortStruct(tmp)
}
}
|