mirror of
				https://github.com/optim-enterprises-bv/vault.git
				synced 2025-10-31 02:28:09 +00:00 
			
		
		
		
	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:
		| @@ -20,6 +20,7 @@ type Backend struct { | ||||
| 	Paths []*Path | ||||
|  | ||||
| 	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 | ||||
|   | ||||
| @@ -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") | ||||
| 		} | ||||
| 	} | ||||
|   | ||||
		Reference in New Issue
	
	Block a user
	 Mitchell Hashimoto
					Mitchell Hashimoto