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:
		| @@ -19,7 +19,8 @@ type Backend struct { | |||||||
| 	// backend is in use). | 	// backend is in use). | ||||||
| 	Paths []*Path | 	Paths []*Path | ||||||
|  |  | ||||||
| 	once sync.Once | 	once    sync.Once | ||||||
|  | 	pathsRe []*regexp.Regexp | ||||||
| } | } | ||||||
|  |  | ||||||
| // Path is a single path that the backend responds to. | // Path is a single path that the backend responds to. | ||||||
| @@ -52,12 +53,9 @@ type Path struct { | |||||||
| } | } | ||||||
|  |  | ||||||
| func (b *Backend) Route(path string) *Path { | func (b *Backend) Route(path string) *Path { | ||||||
| 	regexps := make([]*regexp.Regexp, len(b.Paths)) | 	b.once.Do(b.init) | ||||||
| 	for i, p := range b.Paths { |  | ||||||
| 		regexps[i] = regexp.MustCompile(p.Pattern) |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	for i, re := range regexps { | 	for i, re := range b.pathsRe { | ||||||
| 		if re.MatchString(path) { | 		if re.MatchString(path) { | ||||||
| 			return b.Paths[i] | 			return b.Paths[i] | ||||||
| 		} | 		} | ||||||
| @@ -66,6 +64,13 @@ func (b *Backend) Route(path string) *Path { | |||||||
| 	return nil | 	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. | // FieldSchema is a basic schema to describe the format of a path field. | ||||||
| type FieldSchema struct { | type FieldSchema struct { | ||||||
| 	Type    FieldType | 	Type    FieldType | ||||||
|   | |||||||
| @@ -19,10 +19,15 @@ func BenchmarkBackendRoute(b *testing.B) { | |||||||
| 		backend.Paths = append(backend.Paths, &Path{Pattern: p}) | 		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() | 	b.ResetTimer() | ||||||
|  |  | ||||||
|  | 	// Run through and route. We do a sanity check of the return value | ||||||
| 	for i := 0; i < b.N; i++ { | 	for i := 0; i < b.N; i++ { | ||||||
| 		p := backend.Route("aws/policy/foo") | 		if p := backend.Route("aws/policy/foo"); p == nil { | ||||||
| 		if p == nil { |  | ||||||
| 			b.Fatal("p should not be nil") | 			b.Fatal("p should not be nil") | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user
	 Mitchell Hashimoto
					Mitchell Hashimoto