helper/backend: cache route regexps (98% speedup)

benchmark                 old ns/op     new ns/op     delta
BenchmarkBackendRoute     49144         589           -98.80%
This commit is contained in:
Mitchell Hashimoto 2015-03-13 23:25:17 -07:00
parent 9e7add90b2
commit f19c63de4a
2 changed files with 18 additions and 8 deletions

View File

@ -19,7 +19,8 @@ type Backend struct {
// backend is in use).
Paths []*Path
once sync.Once
once sync.Once
pathsRe []*regexp.Regexp
}
// Path is a single path that the backend responds to.
@ -52,12 +53,9 @@ type Path struct {
}
func (b *Backend) Route(path string) *Path {
regexps := make([]*regexp.Regexp, len(b.Paths))
for i, p := range b.Paths {
regexps[i] = regexp.MustCompile(p.Pattern)
}
b.once.Do(b.init)
for i, re := range regexps {
for i, re := range b.pathsRe {
if re.MatchString(path) {
return b.Paths[i]
}
@ -66,6 +64,13 @@ func (b *Backend) Route(path string) *Path {
return nil
}
func (b *Backend) init() {
b.pathsRe = make([]*regexp.Regexp, len(b.Paths))
for i, p := range b.Paths {
b.pathsRe[i] = regexp.MustCompile(p.Pattern)
}
}
// FieldSchema is a basic schema to describe the format of a path field.
type FieldSchema struct {
Type FieldType

View File

@ -19,10 +19,15 @@ func BenchmarkBackendRoute(b *testing.B) {
backend.Paths = append(backend.Paths, &Path{Pattern: p})
}
// Warm any caches
backend.Route("aws/policy/foo")
// Reset the timer since we did a lot above
b.ResetTimer()
// Run through and route. We do a sanity check of the return value
for i := 0; i < b.N; i++ {
p := backend.Route("aws/policy/foo")
if p == nil {
if p := backend.Route("aws/policy/foo"); p == nil {
b.Fatal("p should not be nil")
}
}