Created
February 20, 2014 12:32
-
-
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...
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 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") | |
} | |
} | |
} |
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
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