Skip to content

Instantly share code, notes, and snippets.

@dougluce
Created July 1, 2015 23:33
Show Gist options
  • Save dougluce/6ad841f8983a314ad366 to your computer and use it in GitHub Desktop.
Save dougluce/6ad841f8983a314ad366 to your computer and use it in GitHub Desktop.
Benchmarking string match-and-return
package p
import (
"net/url"
"testing"
"strings"
"github.com/stretchr/testify/assert"
"github.com/codemodus/parth"
"strconv"
"unicode"
"regexp"
)
func parse_split(name string) (id string){
u, _ := url.Parse(name)
path_elements := strings.Split(u.Path,"/")
id = path_elements[len(path_elements)-1][2:]
return
}
func use_parth_integerwise(name string) (id string){
u, _ := url.Parse(name)
last_path, _ := parth.SegmentToInt(u.Path, -1)
id = strconv.Itoa(last_path)
return
}
func use_parth_stringwise(name string) (id string){
u, _ := url.Parse(name)
last_path, _ := parth.SegmentToString(u.Path, -1)
id = last_path[2:]
return
}
func crawl_string(name string) (id string) {
start := 0
for i, c := range name {
if start != 0 {
if !unicode.IsDigit(c) {
id = name[start:i]
return
}
} else {
if unicode.IsDigit(c) {
start = i
}
}
}
return
}
var m = regexp.MustCompile(`/id(\d+)`)
func regexp_string(name string) (id string) {
id = m.FindStringSubmatch(name)[1]
return
}
func BenchmarkParseSplit(b *testing.B) {
name := "https://itunes.apple.com/us/app/cat-pictures-galore/id832731680?mt=8&uo=4"
for n := 0; n < b.N; n++ {
assert.Equal(b, parse_split(name), "832731680")
}
}
func BenchmarkParthInt(b *testing.B) {
name := "https://itunes.apple.com/us/app/cat-pictures-galore/id832731680?mt=8&uo=4"
for n := 0; n < b.N; n++ {
assert.Equal(b, use_parth_integerwise(name), "832731680")
}
}
func BenchmarkParthString(b *testing.B) {
name := "https://itunes.apple.com/us/app/cat-pictures-galore/id832731680?mt=8&uo=4"
for n := 0; n < b.N; n++ {
assert.Equal(b, use_parth_stringwise(name), "832731680")
}
}
func BenchmarkCrawl(b *testing.B) {
name := "https://itunes.apple.com/us/app/cat-pictures-galore/id832731680?mt=8&uo=4"
for n := 0; n < b.N; n++ {
assert.Equal(b, crawl_string(name), "832731680")
}
}
func BenchmarkRegexp(b *testing.B) {
name := "https://itunes.apple.com/us/app/cat-pictures-galore/id832731680?mt=8&uo=4"
for n := 0; n < b.N; n++ {
assert.Equal(b, "832731680", regexp_string(name))
}
}
func BenchmarkAssert(b *testing.B) {
for n := 0; n < b.N; n++ {
assert.Equal(b, "832731680", "832731680")
}
}
% go test -bench=.
testing: warning: no tests to run
PASS
BenchmarkParseSplit 1000000 1430 ns/op
BenchmarkParthInt 1000000 1402 ns/op
BenchmarkParthString 1000000 1153 ns/op
BenchmarkCrawl 1000000 1253 ns/op
BenchmarkRegexp 1000000 2671 ns/op
BenchmarkAssert 5000000 470 ns/op
ok rtb_go/lyfe-mobile/p 10.832s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment