Skip to content

Instantly share code, notes, and snippets.

@yalue
Created July 23, 2015 14:51
Show Gist options
  • Save yalue/3dcde97867f06cf0eec8 to your computer and use it in GitHub Desktop.
Save yalue/3dcde97867f06cf0eec8 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"regexp"
"time"
)
func getRandomBytes(n uint32) []byte {
rand.Seed(0)
toReturn := make([]byte, n)
for i := 0; i < len(toReturn); i++ {
toReturn[i] = byte(rand.Int())
}
return toReturn
}
var tests = []*regexp.Regexp{
regexp.MustCompile(`abcdef ghijklmnopqrstuv`),
regexp.MustCompile(`abcdef.{0,20}ghijklmnopqrstuv`),
regexp.MustCompile(`(?i)abcdef.{0,20}ghijklmnopqrstuv`),
regexp.MustCompile(`(abc|def).{0,20}ghijklmnopqrstuv`),
}
func main() {
fmt.Printf("Generating random data... ")
data := getRandomBytes(15 * 1024 * 1024)
fmt.Printf("done.\n")
matched := false
var t time.Time
var elapsed time.Duration
for i, re := range tests {
t = time.Now()
matched = re.Match(data)
elapsed = time.Now().Sub(t)
fmt.Printf("Test %d took %f seconds.\n", i, elapsed.Seconds())
if matched {
fmt.Printf("How did a match occur in random data?\n")
}
}
}
@yalue
Copy link
Author

yalue commented Jul 23, 2015

Output for me:

 Generating random data... done.
 Test 0 took 0.003473 seconds.
 Test 1 took 0.003431 seconds.
 Test 2 took 1.799499 seconds.
 Test 3 took 2.017934 seconds.

Go Version:
go version go1.4 linux/amd64

@yalue
Copy link
Author

yalue commented Mar 18, 2017

2017 update: case-insensitive regexes or regexes with | are still much slower:

Generating random data... done.
Test 0 took 0.005006 seconds.
Test 1 took 0.005000 seconds.
Test 2 took 1.326073 seconds.
Test 3 took 1.950103 seconds.

Go Version:
go version go1.8 windows/amd64

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