-
-
Save podanypepa/ae81877cc8d64e453aee5183a0a69d41 to your computer and use it in GitHub Desktop.
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 ( | |
"golang.org/x/exp/slices" | |
"sort" | |
"testing" | |
) | |
func BenchmarkContains(b *testing.B) { | |
data := []string{"pepa", "josef"} | |
for i := 0; i < b.N; i++ { | |
contains(data, "vera") | |
} | |
} | |
func BenchmarkContainsForLoop(b *testing.B) { | |
data := []string{"pepa", "josef"} | |
for i := 0; i < b.N; i++ { | |
contains4(data, "vera") | |
} | |
} | |
func BenchmarkContainsMapStrings(b *testing.B) { | |
data := []string{"pepa", "josef"} | |
for i := 0; i < b.N; i++ { | |
contains2(data, "vera") | |
} | |
} | |
func BenchmarkContainsSearchStrings(b *testing.B) { | |
data := []string{"pepa", "josef"} | |
sort.Strings(data) | |
for i := 0; i < b.N; i++ { | |
contains3(data, "vera") | |
} | |
} | |
func BenchmarkSliceContains(b *testing.B) { | |
data := []string{"pepa", "josef"} | |
for i := 0; i < b.N; i++ { | |
contains5(data, "veru") | |
} | |
} | |
func contains5(data []string, item string) bool { | |
return slices.Contains(data, item) | |
} | |
func contains3(data []string, item string) bool { | |
i := sort.SearchStrings(data, "vera") | |
return i < len(data) && data[i] == "vera" | |
} | |
func contains(elems []string, v string) bool { | |
for _, s := range elems { | |
if v == s { | |
return true | |
} | |
} | |
return false | |
} | |
func contains4(data []string, v string) bool { | |
l := len(data) | |
for i := 0; i < l; i++ { | |
if data[i] == v { | |
return true | |
} | |
} | |
return false | |
} | |
func contains2(slice []string, item string) bool { | |
set := make(map[string]struct{}, len(slice)) | |
for _, s := range slice { | |
set[s] = struct{}{} | |
} | |
_, ok := set[item] | |
return ok | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment