Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omohayui/0e6d29bb62e2fca508fd91ad98a14ac6 to your computer and use it in GitHub Desktop.
Save omohayui/0e6d29bb62e2fca508fd91ad98a14ac6 to your computer and use it in GitHub Desktop.
strings.Contains vs regexp.MatchString (with ToLower and MustCompile)
package bench
import (
"regexp"
"strings"
"testing"
)
var (
inputTexts = []string{
"カワ",
"カワウソ",
"Otter",
"ot",
}
names = []string{"コツメカワウソ",
"オオカワウソ",
"ユーラシアカワウソ",
"ビロードカワウソ",
"ツメナシカワウソ",
"かわうそ",
"otter",
"sea otter",
"liver otter",
"ラッコ",
}
)
func BenchmarkStringsContains(b *testing.B) {
for n := 0; n < b.N; n++ {
for _, inputText := range inputTexts {
for _, name := range names {
strings.Contains(name, strings.ToLower(inputText))
// fmt.Printf("%s, %s: %v\n", name, inputText, strings.Contains(name, strings.ToLower(inputText)))
}
}
}
}
func BenchmarkRegexMatchString(b *testing.B) {
for n := 0; n < b.N; n++ {
for _, inputText := range inputTexts {
re := regexp.MustCompile(`(?i)` + inputText)
for _, name := range names {
re.MatchString(name)
// fmt.Printf("%s, %s: %v\n", name, inputText, re.MatchString(name))
}
}
}
}
@omohayui
Copy link
Author

Result

% go test -bench . -benchmem
BenchmarkStringsContains-8    	  546682	      2154 ns/op	      53 B/op	      10 allocs/op
BenchmarkRegexMatchString-8   	  170746	      7003 ns/op	    4652 B/op	      62 allocs/op

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment