Add regex cache to avoid constant recompilations #190
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Breaking change
Updated the signature of
paths.FindPath
function, to receive a RegexCache interface as a parameter.The problem
Every time a path search is performed, each path and its fragments get a new regex compilation. For general validation purpose, this is not a big deal. The problem is, when validating the same document for different requests, hundreds of times per minute. The CPU pressure and memory usage can grow significantly for allocating every regex compilation.
The solution
To avoid all the regex recompilation, a new
ValidationOption
has been added to allow users to attach a Regex Cache interface, which has aLoad
and aStore
method. The functionconfig.WithRegexCache
set the ValidationOptions. The cache is optional, so the end user that simply calls theNewValidator*
function, nothing's changed.Test and benchmarking
Every test is passing. Tests that call the
FindPath
function have been updated to include a per-validator cache, and some of them are cache-free. Added tests that check how many times the cache was accessed.A benchmark was added to the
validate_parameter_test.go
file, that makes a sync validation through every 5 parameter validator. The results show a 50% decrease in execution time, and a 3.8x improvement in memory allocations:Adding a cache
To add a RegexCache, just call the WithRegexCache:
A sync.Map is full compatible with the cache, as it is a interface with Load and Store functions. Cleaning and managing the cache staleness must be done by the end user.