Last active
December 9, 2023 06:22
-
-
Save Ozoniuss/1447728abde9bf9730d539c3de077e55 to your computer and use it in GitHub Desktop.
Comparing all string vs first letter
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 ( | |
"bufio" | |
"os" | |
"testing" | |
) | |
var ret = "" | |
func getWords() []string { | |
// 172k words | |
f, _ := os.Open("wordlist.txt") | |
defer f.Close() | |
words := []string{} | |
s := bufio.NewScanner(f) | |
for s.Scan() { | |
words = append(words, s.Text()) | |
} | |
return words | |
} | |
var allWords []string = getWords() | |
func BenchmarkComparisonLongWord(b *testing.B) { | |
r := "" | |
for n := 0; n < b.N; n++ { | |
for _, w := range allWords { | |
if w == "banana" { | |
r = "hi" | |
} else { | |
r = "no" | |
} | |
} | |
} | |
ret = r | |
} | |
func BenchmarkComparisonShortLetter(b *testing.B) { | |
r := "" | |
for n := 0; n < b.N; n++ { | |
for _, w := range allWords { | |
if w == "b" { | |
r = "hi" | |
} else { | |
r = "no" | |
} | |
} | |
} | |
ret = r | |
} | |
func BenchmarkComparisonFirst(b *testing.B) { | |
r := "" | |
for n := 0; n < b.N; n++ { | |
for _, w := range allWords { | |
if w[0] == 'b' { | |
r = "hi" | |
} else { | |
r = "no" | |
} | |
} | |
} | |
ret = r | |
} | |
$ go test -bench=. -benchmem main_test.go | |
// goos: windows | |
// goarch: amd64 | |
// cpu: AMD Ryzen 7 5800H with Radeon Graphics | |
// BenchmarkComparisonLongWord-16 5324 214208 ns/op 0 B/op 0 allocs/op | |
// BenchmarkComparisonShortLetter-16 9544 128170 ns/op 0 B/op 0 allocs/op | |
// BenchmarkComparisonFirst-16 10000 107055 ns/op 0 B/op 0 allocs/op | |
// PASS | |
// ok command-line-arguments 3.627s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment