Speed up ERB expression BLOCK_EXPR regex #48414
Merged
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.
I noticed that during our application's boot we were spending more time than desirable matching against this BLOCK_EXPR regex. This was slower than necessary because even though this regex engine only cares about the end of the string, Ruby's regex engine only works forward, and this regex would match whitespace anywhere inside the string using two ambiguous adjacent whitespace repetitions.
We don't expect untrusted code here (this is Ruby in our ERB which we are going to execute), but with realistic strings this still causes unnecessary backtracking.
This commit fixes the problem by removing the initial "\s*" (since this is optional we don't need to capture it, we can just find the match later if it exists) and replacing the following "\s+" with just "\s" (similarly we don't care how many whitespace appear in a row, we can just match later if there is more than one).
Testing against all the ERB expressions in our app this is 10x faster: from 1.5 seconds to 0.1 seconds.