Skip to content

Instantly share code, notes, and snippets.

@omohayui
Created June 29, 2023 12:41
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/3af060173ec7b0393c221a1fad6870fb to your computer and use it in GitHub Desktop.
Save omohayui/3af060173ec7b0393c221a1fad6870fb to your computer and use it in GitHub Desktop.
strings.Contains vs regexp.MatchString
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, inputText)
// fmt.Printf("%s, %s: %v\n", name, inputText, strings.Contains(name, inputText))
}
}
}
}
func BenchmarkRegexMatchString(b *testing.B) {
for n := 0; n < b.N; n++ {
for _, inputText := range inputTexts {
for _, name := range names {
regexp.MatchString(inputText, name)
// fmt.Printf("%s, %s: %v\n", name, inputText, res)
}
}
}
}
@omohayui
Copy link
Author

Result

% go test -bench . -benchmem
BenchmarkStringsContains-8    	 2360593	       479.9 ns/op	       0 B/op	       0 allocs/op
BenchmarkRegexMatchString-8   	   39990	     28784 ns/op	   46446 B/op	     620 allocs/op

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