Skip to content

Instantly share code, notes, and snippets.

@dgryski
Created February 13, 2017 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgryski/9b84918084ea7a885f184869e957bfa5 to your computer and use it in GitHub Desktop.
Save dgryski/9b84918084ea7a885f184869e957bfa5 to your computer and use it in GitHub Desktop.
package main
import (
"strings"
"testing"
)
var m = map[string]bool{"hello.goodbye": true}
func old(req string, filter map[string]bool) string {
// Try to match path from full string to less levels
var pathSplitted []string = strings.Split(req, "/")
for curDepth := len(pathSplitted); curDepth > 0; curDepth-- {
path := strings.Join(pathSplitted[0:curDepth], ".")
if filter[path] {
return path
}
}
return ""
}
func faster(req string, filter map[string]bool) string {
// Try to match path from full string to less levels
var metric = strings.Replace(req, "/", ".", -1)
for metric != "" {
if filter[metric] {
return metric
}
idx := strings.LastIndexByte(metric, '.')
if idx == -1 {
break
}
metric = metric[:idx]
}
return ""
}
func TestFaster(t *testing.T) {
if old("hello/goodbye/foo/bar/baz/zot", m) != faster("hello/goodbye/foo/bar/baz/zot", m) {
t.Error("fail")
}
}
var sink int
func BenchmarkOld(b *testing.B) {
for i := 0; i < b.N; i++ {
sink += len(old("foo/bar/baz/zot", m))
}
}
func BenchmarkFaster(b *testing.B) {
for i := 0; i < b.N; i++ {
sink += len(faster("foo/bar/baz/zot", m))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment