Skip to content

Commit d8e11e9

Browse files
committed
Speed up ERB expression BLOCK_EXPR regex
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.
1 parent 43852db commit d8e11e9

File tree

1 file changed

+1
-1
lines changed
  • actionview/lib/action_view/template/handlers/erb

1 file changed

+1
-1
lines changed

actionview/lib/action_view/template/handlers/erb/erubi.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def add_text(text)
4242
end
4343
end
4444

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

4747
def add_expression(indicator, code)
4848
flush_newline_if_pending(src)

0 commit comments

Comments
 (0)