From fad58ef436bb9a516ea8364d9398cb6f6876d784 Mon Sep 17 00:00:00 2001 From: Watson Date: Wed, 16 Mar 2022 12:41:00 +0900 Subject: [PATCH] Use String#match? instead of String#=~ to reduce allocation for backreferecne MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Test code ```ruby require 'benchmark/ips' WhitespaceOrNothing = /\A\s*\z/ token = " " * 20 token =~ WhitespaceOrNothing Benchmark.ips do |x| x.report("=~") { token =~ WhitespaceOrNothing } x.report("match?") { token.match?(WhitespaceOrNothing) } x.compare! end ``` ## Result ``` Warming up -------------------------------------- =~ 271.356k i/100ms match? 579.655k i/100ms Calculating ------------------------------------- =~ 2.717M (± 0.4%) i/s - 13.839M in 5.092947s match? 5.695M (± 1.6%) i/s - 28.983M in 5.090640s Comparison: match?: 5694747.3 i/s =~: 2717370.9 i/s - 2.10x (± 0.00) slower ``` --- lib/liquid/block_body.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/liquid/block_body.rb b/lib/liquid/block_body.rb index 2921ce88..d8c7e453 100644 --- a/lib/liquid/block_body.rb +++ b/lib/liquid/block_body.rb @@ -37,7 +37,7 @@ module Liquid private def parse_for_liquid_tag(tokenizer, parse_context) while (token = tokenizer.shift) - unless token.empty? || token =~ WhitespaceOrNothing + unless token.empty? || token.match?(WhitespaceOrNothing) unless token =~ LiquidTagToken # line isn't empty but didn't match tag syntax, yield and let the # caller raise a syntax error @@ -150,7 +150,7 @@ module Liquid end parse_context.trim_whitespace = false @nodelist << token - @blank &&= !!(token =~ WhitespaceOrNothing) + @blank &&= token.match?(WhitespaceOrNothing) end parse_context.line_number = tokenizer.line_number end