Created
August 23, 2018 16:27
-
-
Save xeoncross/2464ef7cce26a9576a004482785c1466 to your computer and use it in GitHub Desktop.
Testing searching through thousands of strings looking for indexes or keys - Go - golang https://play.golang.org/p/1qXo5kT6LfL
This file contains hidden or 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 ( | |
"errors" | |
"fmt" | |
"log" | |
"math/rand" | |
"sort" | |
"time" | |
) | |
func main() { | |
var strings []string | |
size := 5 | |
// X random strings | |
for i := 0; i < 10000; i++ { | |
b, err := getBytes(size) | |
if err != nil { | |
log.Fatal(err) | |
} | |
strings = append(strings, string(b)) | |
} | |
start := time.Now() | |
fmt.Printf("Searching %d strings...\n", len(strings)) | |
sort.Strings(strings) // So they can be searched faster | |
var x int64 | |
for { | |
b, err := getBytes(size) | |
if err != nil { | |
log.Fatal(err) | |
} | |
key := string(b) | |
i := sort.SearchStrings(strings, key) | |
if i < len(strings) && strings[i] == key { | |
log.Println(strings[i] + " == " + key) | |
break | |
} | |
x++ | |
if x%10000000 == 0 { | |
fmt.Println(x) | |
} | |
} | |
fmt.Println(time.Since(start)) | |
} | |
func getBytes(n int) (b []byte, err error) { | |
b = make([]byte, n) | |
n, err = rand.Read(b) | |
if err != nil { | |
return | |
} | |
if n != len(b) { | |
err = errors.New("not enough bytes read") | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment