Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save smagch/9210816 to your computer and use it in GitHub Desktop.
Golang: simple string processing vs char map vs regexp

simple string processing vs char map vs regexp

BenchmarkRune	20000000	       152 ns/op
BenchmarkMap	 5000000	       346 ns/op
BenchmarkRegexp	 1000000	      1034 ns/op
package main
import (
"regexp"
"strconv"
"testing"
)
type matches struct {
r *regexp.Regexp
intMap map[rune]bool
}
func New() *matches {
return &matches{
regexp.MustCompile(`^[0-9]+$`),
map[rune]bool{
'0': true,
'1': true,
'2': true,
'3': true,
'4': true,
'5': true,
'6': true,
'7': true,
'8': true,
'9': true,
},
}
}
func isDigit(r rune) bool {
return '0' <= r && r <= '9'
}
func (m *matches) isStringDigit(s string) bool {
for _, r := range s {
if !isDigit(r) {
return false
}
}
return true
}
func (m *matches) MatchString(s string) bool {
return m.r.MatchString(s)
}
func (m *matches) hasStringInMap(s string) bool {
for _, r := range s {
if _, ok := m.intMap[r]; !ok {
return false
}
}
return true
}
func BenchmarkRune(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 BenchmarkMap(b *testing.B) {
var total int
m := New()
for i := 0; i < b.N; i++ {
num := strconv.Itoa(i)
if m.hasStringInMap(num) {
total++
}
}
}
func BenchmarkRegexp(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