In this approach, we'll find out how to most efficiently determine the Scrabble Score in Go.
The approaches page lists two idiomatic approaches to this exercise:
For our performance investigation, we'll also include a third approach that uses a switch
on strings.
Benchmarks
To benchmark the approaches, we ran the following Benchmark code for each approach:
func BenchmarkScore(b *testing.B) {
if testing.Short() {
b.Skip("skipping benchmark in short mode.")
}
for i := 0; i < b.N; i++ {
for _, test := range scrabbleScoreTests {
Score(test.input)
}
}
}
and received the following results:
map
BenchmarkScore-12 1544814 711.7 ns/op 0 B/op 0 allocs/op
switch on runes
BenchmarkScore-12 4171696 242.1 ns/op 0 B/op 0 allocs/op
switch on strings
BenchmarkScore-12 413484 2527 ns/op 1088 B/op 12 allocs/op
Generally, the fewer bytes allocated per op (B/op
) the faster (i.e. the fewer ns/op) the implementation.
More info on reading benchmarks can be found here.
Using switch
on runes was about three times faster than the next fastest approach, which was using a map
.
Using a switch
on each letter being a separate string was over ten times slower than switching on runes.
11th Sep 2024
·
Found it useful?