Comparison betewen the "map as a set" and a string slice accessed by two functions. "Sort" based and "for" based search included too.
Use this command to run the benchmark tests
go test -bench=.
| package main | |
| import ( | |
| "sort" | |
| ) | |
| func main() {} | |
| func containsWithSort(s []string, searchterm string) bool { | |
| i := sort.SearchStrings(s, searchterm) | |
| return i < len(s) && s[i] == searchterm | |
| } | |
| func containsWithFor(s []string, e string) bool { | |
| for _, a := range s { | |
| if a == e { | |
| return true | |
| } | |
| } | |
| return false | |
| } |
| package main | |
| import ( | |
| "testing" | |
| ) | |
| var stringSlice = []string{"hello", "world", "good", "bad", "red", "back"} | |
| var mapWithEmptyStruct = map[string]struct{}{ | |
| "hello": {}, | |
| "world": {}, | |
| "good": {}, | |
| "bad": {}, | |
| "red": {}, | |
| "back": {}, | |
| } | |
| const ( | |
| notElement = "notInTheListOrMap" | |
| element = "good" | |
| ) | |
| func BenchmarkContainsWithSortNotFound(b *testing.B) { | |
| for i := 0; i < b.N; i++ { | |
| containsWithSort(stringSlice, notElement) | |
| } | |
| } | |
| func BenchmarkContainsWithSortFound(b *testing.B) { | |
| for i := 0; i < b.N; i++ { | |
| containsWithSort(stringSlice, element) | |
| } | |
| } | |
| func BenchmarkContainsWithForNotFound(b *testing.B) { | |
| for i := 0; i < b.N; i++ { | |
| containsWithFor(stringSlice, notElement) | |
| } | |
| } | |
| func BenchmarkContainsWithForFound(b *testing.B) { | |
| for i := 0; i < b.N; i++ { | |
| containsWithFor(stringSlice, element) | |
| } | |
| } | |
| func BenchmarkContainsMapNotFound(b *testing.B) { | |
| for i := 0; i < b.N; i++ { | |
| _, _ = mapWithEmptyStruct[notElement] | |
| } | |
| } | |
| func BenchmarkContainsMapFound(b *testing.B) { | |
| for i := 0; i < b.N; i++ { | |
| _, _ = mapWithEmptyStruct[element] | |
| } | |
| } |
For anyone viewing these and interested at a glance, these were my benchmark results. Obviously, these will vary with hardware and current load so run them yourself for a better idea.
CPU: AMD Ryzen 7 3700X
Run 1
Run 2