Skip to content

Instantly share code, notes, and snippets.

@bakins
Created April 2, 2019 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bakins/f4d342d1cc93f4911ffd4efa9d93ecab to your computer and use it in GitHub Desktop.
Save bakins/f4d342d1cc93f4911ffd4efa9d93ecab to your computer and use it in GitHub Desktop.
compare escapeMetricName
package main
import (
"regexp"
"testing"
)
var illegalCharsRE = regexp.MustCompile(`[^a-zA-Z0-9_]`)
func regexVersion(metricName string) string {
if len(metricName) > 0 && metricName[0] >= '0' && metricName[0] <= '9' {
metricName = "_" + metricName
}
metricName = illegalCharsRE.ReplaceAllString(metricName, "_")
return metricName
}
func hackVersion(metricName string) string {
if len(metricName) > 0 && metricName[0] >= '0' && metricName[0] <= '9' {
metricName = "_" + metricName
}
out := make([]byte, len(metricName))
j := 0
for _, c := range metricName {
if (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') {
out[j] = byte(c)
} else {
out[j] = byte('_')
}
j++
}
return string(out[:j])
}
func benmarkRegex(b *testing.B, metricName string) {
for n := 0; n < b.N; n++ {
regexVersion(metricName)
}
}
func benmarkHack(b *testing.B, metricName string) {
for n := 0; n < b.N; n++ {
hackVersion(metricName)
}
}
func BenchmarkRegexClean(b *testing.B) { benmarkRegex(b, "clean") }
func BenchmarkHackClean(b *testing.B) { benmarkHack(b, "clean") }
func BenchmarkRegexDigit(b *testing.B) { benmarkRegex(b, "0starts_with_digit") }
func BenchmarkHackDigit(b *testing.B) { benmarkHack(b, "0starts_with_digit") }
func BenchmarkRegexDot(b *testing.B) { benmarkRegex(b, "with.dot") }
func BenchmarkHackDot(b *testing.B) { benmarkHack(b, "with.dot") }
func BenchmarkRegexEmoji(b *testing.B) { benmarkRegex(b, "with😱emoji") }
func BenchmarkHackEmoji(b *testing.B) { benmarkHack(b, "with😱emoji") }
statsd-exporter-compare bakins$ go test -bench=. -test.benchmem
goos: darwin
goarch: amd64
BenchmarkRegexClean-12 5000000 251 ns/op 32 B/op 3 allocs/op
BenchmarkHackClean-12 50000000 30.1 ns/op 10 B/op 2 allocs/op
BenchmarkRegexDigit-12 2000000 633 ns/op 113 B/op 4 allocs/op
BenchmarkHackDigit-12 20000000 74.4 ns/op 64 B/op 2 allocs/op
BenchmarkRegexDot-12 3000000 411 ns/op 32 B/op 3 allocs/op
BenchmarkHackDot-12 50000000 35.3 ns/op 16 B/op 2 allocs/op
BenchmarkRegexEmoji-12 3000000 514 ns/op 56 B/op 4 allocs/op
BenchmarkHackEmoji-12 30000000 49.5 ns/op 32 B/op 2 allocs/op
PASS
ok _/Users/bakins/src/statsd-exporter-compare 13.593s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment