Skip to content

Instantly share code, notes, and snippets.

@TimSimmons
Created March 18, 2022 20:59
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 TimSimmons/da215a8a4e6361df8c82544e1d1f063f to your computer and use it in GitHub Desktop.
Save TimSimmons/da215a8a4e6361df8c82544e1d1f063f to your computer and use it in GitHub Desktop.
Is a regex with (things|in|it) slow vs iterating a slice?
$ go test -bench=.
goos: darwin
goarch: amd64
pkg: example.com/test
cpu: VirtualApple @ 2.50GHz
BenchmarkRegexOne-8 18224203 65.00 ns/op
BenchmarkSliceOne-8 391034821 3.078 ns/op
BenchmarkRegexThree-8 12396331 96.85 ns/op
BenchmarkSliceThree-8 270857839 4.426 ns/op
BenchmarkRegexFive-8 11875524 100.4 ns/op
BenchmarkSliceFive-8 100000000 10.85 ns/op
PASS
ok example.com/test 8.417s
package main
import (
"regexp"
"testing"
)
func regex(r *regexp.Regexp, s string) bool {
return r.MatchString(s)
}
func iterate(slice []string, s string) bool {
for _, m := range slice {
if m == s {
return true
}
}
return false
}
func BenchmarkRegexOne(b *testing.B) {
r, _ := regexp.Compile("(one|two|three|four|five)")
for n := 0; n < b.N; n++ {
regex(r, "one")
}
}
func BenchmarkSliceOne(b *testing.B) {
slice := []string{"one", "two", "three", "four", "five"}
for n := 0; n < b.N; n++ {
iterate(slice, "one")
}
}
func BenchmarkRegexThree(b *testing.B) {
r, _ := regexp.Compile("(one|two|three|four|five)")
for n := 0; n < b.N; n++ {
regex(r, "three")
}
}
func BenchmarkSliceThree(b *testing.B) {
slice := []string{"one", "two", "three", "four", "five"}
for n := 0; n < b.N; n++ {
iterate(slice, "three")
}
}
func BenchmarkRegexFive(b *testing.B) {
r, _ := regexp.Compile("(one|two|three|four|five)")
for n := 0; n < b.N; n++ {
regex(r, "five")
}
}
func BenchmarkSliceFive(b *testing.B) {
slice := []string{"one", "two", "three", "four", "five"}
for n := 0; n < b.N; n++ {
iterate(slice, "five")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment