Skip to content

Instantly share code, notes, and snippets.

@gkristic
Created February 20, 2014 12:32
Show Gist options
  • Save gkristic/9112493 to your computer and use it in GitHub Desktop.
Save gkristic/9112493 to your computer and use it in GitHub Desktop.
Regular expressions are flexible, but that obviously comes with a time penalty. If you need to check for very specific cases, you may be better off writing the function yourself. Check this out...
package main
import (
"regexp"
"testing"
)
func matches(str, pattern string) bool {
p, s := 0, 0
matches := true
for ; matches && p < len(pattern) && s < len(str); p++ {
if pattern[p] == '%' {
for s < len(str) && str[s] != '.' {
s++
}
} else {
matches = (str[s] == pattern[p])
s++
}
}
return matches && p == len(pattern) && s == len(str)
}
var str = "os.disk.myfancydiskdrive.tput"
var re = regexp.MustCompile("^os.disk.[^.]*.tput$")
func BenchmarkMatch(b *testing.B) {
for i := 0; i < b.N; i++ {
if !matches(str, "os.disk.%.tput") {
b.Fatal("string should match")
}
}
}
func BenchmarkRegex(b *testing.B) {
for i := 0; i < b.N; i++ {
if !re.MatchString(str) {
b.Fatal("string should match")
}
}
}
BenchmarkMatch 20000000 76.7 ns/op
BenchmarkRegex 500000 3119 ns/op
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment