BenchmarkFirstWithStringMatch 20000000 127 ns/op
BenchmarkFirstWithRegexpMatch 1000000 1067 ns/op
Last active
August 29, 2015 13:56
-
-
Save smagch/9210646 to your computer and use it in GitHub Desktop.
Golang: simple string processing vs regexp
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 ( | |
| "regexp" | |
| "strconv" | |
| "testing" | |
| ) | |
| type matches struct { | |
| r *regexp.Regexp | |
| intMap map[byte]bool | |
| } | |
| func New() *matches { | |
| return &matches{ | |
| regexp.MustCompile(`^[0-9]+$`), | |
| map[byte]bool{ | |
| '0': true, | |
| '1': true, | |
| '2': true, | |
| '3': true, | |
| '4': true, | |
| '5': true, | |
| '6': true, | |
| '7': true, | |
| '8': true, | |
| '9': true, | |
| }, | |
| } | |
| } | |
| func (m *matches) isDigit(ch byte) bool { | |
| return '0' <= ch && ch <= '9' | |
| } | |
| func (m *matches) isStringDigit(str string) bool { | |
| for i, l := 0, len(str); i < l; i++ { | |
| if !m.isDigit(str[i]) { | |
| return false | |
| } | |
| } | |
| return true | |
| } | |
| func (m *matches) MatchString(str string) bool { | |
| return m.r.MatchString(str) | |
| } | |
| func BenchmarkFirstWithStringMatch(b *testing.B) { | |
| var total int | |
| m := New() | |
| for i := 0; i < b.N; i++ { | |
| num := strconv.Itoa(i) | |
| if m.isStringDigit(num) { | |
| total++ | |
| } | |
| } | |
| } | |
| func BenchmarkFirstWithRegexpMatch(b *testing.B) { | |
| var total int | |
| m := New() | |
| for i := 0; i < b.N; i++ { | |
| num := strconv.Itoa(i) | |
| if m.MatchString(num) { | |
| total++ | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment