Skip to content

Commit

Permalink
Speed up ERB expression BLOCK_EXPR regex
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jhawthorn committed Jun 6, 2023
1 parent 43852db commit d8e11e9
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion actionview/lib/action_view/template/handlers/erb/erubi.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def add_text(text)
end
end

BLOCK_EXPR = /\s*((\s+|\))do|\{)(\s*\|[^|]*\|)?\s*\Z/
BLOCK_EXPR = /((\s|\))do|\{)(\s*\|[^|]*\|)?\s*\Z/

def add_expression(indicator, code)
flush_newline_if_pending(src)
Expand Down

0 comments on commit d8e11e9

Please sign in to comment.