Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speed up ERB expression BLOCK_EXPR regex #48414

Merged
merged 1 commit into from
Jun 7, 2023

Conversation

jhawthorn
Copy link
Member

@jhawthorn jhawthorn commented Jun 6, 2023

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.

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.
@rails-bot rails-bot bot added the actionview label Jun 6, 2023
@jhawthorn jhawthorn merged commit 55c3066 into rails:main Jun 7, 2023
9 checks passed
@jhawthorn jhawthorn deleted the faster_block_expr branch June 7, 2023 16:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants