Skip to content

Instantly share code, notes, and snippets.

@kevinschoon
Last active February 19, 2016 22:06
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 kevinschoon/31a283828a5acdc14e66 to your computer and use it in GitHub Desktop.
Save kevinschoon/31a283828a5acdc14e66 to your computer and use it in GitHub Desktop.
search test
package main
import (
"fmt"
"io/ioutil"
"math/rand"
"strings"
"time"
)
type MapReader struct {
words map[string]bool
}
func (mr *MapReader) search(term string) {
if _, exists := mr.words[term]; exists {
return
}
panic(fmt.Errorf("Term %s not found", term))
}
type ArrayReader struct {
words []string
}
func (ar *ArrayReader) Search(term string) {
for _, word := range ar.words {
if word == term {
return
}
}
panic(fmt.Errorf("Term %s not found", term))
}
func main() {
rand.Seed(int64(time.Now().Nanosecond()))
data, _ := ioutil.ReadFile("/usr/share/dict/words")
loaded := strings.Split(string(data), "\n")
mr := &MapReader{words: make(map[string]bool)}
for _, word := range loaded { // Load all words into map
mr.words[word] = true
}
ar := &ArrayReader{words: loaded}
lookupWords := make([]string, 0)
for i := 0; i < 50000; i++ { // Select 50000 words at random to search for
lookupWords = append(lookupWords, loaded[rand.Intn(len(loaded))])
}
var (
mapTime time.Duration
arrayTime time.Duration
)
started := time.Now()
for _, term := range lookupWords {
ar.Search(term)
}
arrayTime = time.Since(started)
started = time.Now()
for _, term := range loaded {
mr.search(term)
}
mapTime = time.Since(started)
fmt.Println("-----------------")
fmt.Println("Array lookup took: ", arrayTime)
fmt.Println("Map lookup took: ", mapTime)
fmt.Println("-----------------")
/*
-----------------
Array lookup took: 8.14893531s
Map lookup took: 6.79899ms
-----------------
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment