Created
February 13, 2017 09:21
-
-
Save dgryski/9b84918084ea7a885f184869e957bfa5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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