Created
January 21, 2020 15:17
-
-
Save mem/c3da6cc9635ef0446137fafe97aead35 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"bytes" | |
"fmt" | |
"regexp" | |
"strings" | |
"testing" | |
) | |
const ( | |
str1 = "aaaa" | |
str2 = "bbbb" | |
) | |
var inputs = buildInputs("aaax", []string{str1, str2}, 128, 256, 512, 8192, 32768) | |
var matched bool | |
func BenchmarkRegex(b *testing.B) { | |
re := regexp.MustCompile("(" + str1 + "|" + str2 + ")") | |
b.ResetTimer() | |
for name, input := range inputs { | |
b.Run(name, func(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
if re.Match(input) { | |
matched = true | |
} | |
} | |
}) | |
} | |
} | |
func BenchmarkByteContains(b *testing.B) { | |
for name, input := range inputs { | |
b.Run(name, func(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
if bytes.Contains(input, []byte(str1)) || bytes.Contains(input, []byte(str2)) { | |
matched = true | |
} | |
} | |
}) | |
} | |
} | |
func gen(str string, n int) string { | |
var b strings.Builder | |
for i := 0; i < n; i++ { | |
b.WriteString(str) | |
} | |
return b.String() | |
} | |
func buildInputs(junk string, needles []string, prefixLens ...int) map[string][]byte { | |
inputs := make(map[string][]byte) | |
for _, pl := range prefixLens { | |
for _, str := range needles { | |
prefix := gen(junk, pl/len(junk)) | |
name := fmt.Sprintf("prefix %d + %s", len(prefix), str) | |
inputs[name] = []byte(prefix + str) | |
} | |
} | |
return inputs | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment