Created
December 2, 2020 15:57
-
-
Save ken39arg/bdd7812de4b14a53abc730f41d913b86 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
package phrasetrie | |
import ( | |
"math/rand" | |
"sort" | |
"testing" | |
) | |
type mp map[int]struct{} | |
func newMap(vs []int) mp { | |
m := make(map[int]struct{}, len(vs)) | |
for _, k := range vs { | |
m[k] = struct{}{} | |
} | |
return m | |
} | |
func (m mp) has(k int) bool { | |
_, ok := m[k] | |
return ok | |
} | |
type srange []int | |
func newSlice(vs []int) srange { | |
item := make([]int, len(vs)) | |
copy(item, vs) | |
sort.Sort(sort.IntSlice(item)) | |
return item | |
} | |
func (s srange) has(k int) bool { | |
for _, v := range s { | |
if k == v { | |
return true | |
} | |
if k < v { | |
return false | |
} | |
} | |
return false | |
} | |
type smp []bool | |
func newSliceMap(vs []int) smp { | |
max := 0 | |
for _, v := range vs { | |
if max < v { | |
max = v | |
} | |
} | |
m := make([]bool, max+1) | |
for _, v := range vs { | |
m[v] = true | |
} | |
return m | |
} | |
func (s smp) has(k int) bool { | |
return s[k] | |
} | |
func makeSlice(size, max int) []int { | |
m := make([]int, size) | |
e := make(map[int]bool, size) | |
for i := range m { | |
for m[i] > 0 { | |
v := rand.Intn(max) | |
if !e[v] { | |
m[i] = v | |
e[v] = true | |
} | |
} | |
} | |
if !e[max] { | |
m[rand.Intn(size)] = max | |
} | |
return m | |
} | |
func BenchmarkMap(b *testing.B) { | |
for _, c := range []struct { | |
name string | |
max int | |
data []int | |
}{ | |
{"30_255", 255, makeSlice(30, 255)}, | |
{"100_255", 255, makeSlice(100, 255)}, | |
{"255_255", 255, makeSlice(255, 255)}, | |
// {"30_511", 511, makeSlice(30, 511)}, | |
// {"100_511", 511, makeSlice(100, 511)}, | |
// {"300_511", 511, makeSlice(200, 511)}, | |
} { | |
b.Run("map-"+c.name, func(b *testing.B) { | |
t := newMap(c.data) | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
v := rand.Intn(c.max) | |
t.has(v) | |
} | |
}) | |
b.Run("slice-"+c.name, func(b *testing.B) { | |
t := newSlice(c.data) | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
v := rand.Intn(c.max) | |
t.has(v) | |
} | |
}) | |
b.Run("sliceMap-"+c.name, func(b *testing.B) { | |
t := newSliceMap(c.data) | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
v := rand.Intn(c.max) | |
t.has(v) | |
} | |
}) | |
} | |
} |
Author
ken39arg
commented
Dec 2, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment