Skip to content

Instantly share code, notes, and snippets.

@smagch
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save smagch/9414312 to your computer and use it in GitHub Desktop.

Select an option

Save smagch/9414312 to your computer and use it in GitHub Desktop.
Golang: Suffix match benchmark, regexp vs rune match
BenchmarkSuffixMatchByRuneLength10	10000000	       226 ns/op
BenchmarkSuffixMatchByRuneLength30	 5000000	       630 ns/op
BenchmarkSuffixMatchByRegexpLength10	 1000000	      2033 ns/op
BenchmarkSuffixMatchByRegexpLength30	  500000	      4863 ns/op
package main
import (
"regexp"
"testing"
)
func isDigit(r rune) bool {
return '0' <= r && r <= '9'
}
type RuneMatcherFunc func(r rune) bool
type SuffixMatcher struct {
suffix string
f RuneMatcherFunc
}
func (m *SuffixMatcher) Match(s string) int {
d := len(s) - len(m.suffix)
// at least 1 character is required to match suffix and matcher
if d < 1 {
return -1
}
for i, r := range s {
if i > d {
return -1
}
// peek string to match to suffix pattern
if i != 0 && m.suffix == s[i:i+len(m.suffix)] {
return i + len(m.suffix)
}
if !m.f(r) {
return -1
}
}
return -1
}
func BenchmarkSuffixMatchByRuneLength10(b *testing.B) {
b.StopTimer()
m := &SuffixMatcher{"/about", RuneMatcherFunc(isDigit)}
b.StartTimer()
for i := 0; i < b.N; i++ {
if index := m.Match("0123456789/about"); index != 16 {
panic("broken matcher")
}
}
}
func BenchmarkSuffixMatchByRuneLength30(b *testing.B) {
b.StopTimer()
m := &SuffixMatcher{"/about", RuneMatcherFunc(isDigit)}
b.StartTimer()
for i := 0; i < b.N; i++ {
if index := m.Match("012345678901234567890123456789/about"); index != 36 {
panic("broken matcher")
}
}
}
func BenchmarkSuffixMatchByRegexpLength10(b *testing.B) {
b.StopTimer()
r := regexp.MustCompile(`^\d+\/about$`)
b.StartTimer()
for i := 0; i < b.N; i++ {
if ok := r.MatchString("0123456789/about"); !ok {
panic("broken regexp matcher")
}
}
}
func BenchmarkSuffixMatchByRegexpLength30(b *testing.B) {
b.StopTimer()
r := regexp.MustCompile(`^\d+\/about$`)
b.StartTimer()
for i := 0; i < b.N; i++ {
if ok := r.MatchString("012345678901234567890123456789/about"); !ok {
panic("broken regexp matcher")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment