Created
March 18, 2022 20:59
-
-
Save TimSimmons/da215a8a4e6361df8c82544e1d1f063f to your computer and use it in GitHub Desktop.
Is a regex with (things|in|it) slow vs iterating a slice?
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
$ 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 |
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 ( | |
"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