From 1667c1180e8f99eb4c515053c009fba74741e25c Mon Sep 17 00:00:00 2001 From: Watson Date: Sat, 12 Mar 2022 01:41:12 +0900 Subject: [PATCH] Use start_with? and end_with? to detect SQUARE_BRAKET MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Test code ```ruby require 'benchmark/ips' SQUARE_BRACKETED = /\A\[(.*)\]\z/m markup = "[product.catchall]" Benchmark.ips do |x| x.report("SQUARE_BRACKETED") { if markup =~ SQUARE_BRACKETED Regexp.last_match(1) end } x.report("start/end_with?") { if markup&.start_with?('[') && markup&.end_with?(']') markup[1..-2] end } x.compare! end ``` ## Result ``` Warming up -------------------------------------- SQUARE_BRACKETED 261.300k i/100ms start/end_with? 548.813k i/100ms Calculating ------------------------------------- SQUARE_BRACKETED 2.632M (± 0.6%) i/s - 13.326M in 5.064085s start/end_with? 5.471M (± 0.5%) i/s - 27.441M in 5.015770s Comparison: start/end_with?: 5470994.1 i/s SQUARE_BRACKETED: 2631642.3 i/s - 2.08x (± 0.00) slower ``` --- lib/liquid/variable_lookup.rb | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/lib/liquid/variable_lookup.rb b/lib/liquid/variable_lookup.rb index 9d5dba68..775b002e 100644 --- a/lib/liquid/variable_lookup.rb +++ b/lib/liquid/variable_lookup.rb @@ -2,8 +2,7 @@ module Liquid class VariableLookup - SQUARE_BRACKETED = /\A\[(.*)\]\z/m - COMMAND_METHODS = ['size', 'first', 'last'].freeze + COMMAND_METHODS = ['size', 'first', 'last'].freeze attr_reader :name, :lookups @@ -15,8 +14,8 @@ module Liquid lookups = markup.scan(VariableParser) name = lookups.shift - if name =~ SQUARE_BRACKETED - name = Expression.parse(Regexp.last_match(1)) + if name&.start_with?('[') && name&.end_with?(']') + name = Expression.parse(name[1..-2]) end @name = name @@ -25,8 +24,8 @@ module Liquid @lookups.each_index do |i| lookup = lookups[i] - if lookup =~ SQUARE_BRACKETED - lookups[i] = Expression.parse(Regexp.last_match(1)) + if lookup&.start_with?('[') && lookup&.end_with?(']') + lookups[i] = Expression.parse(lookup[1..-2]) elsif COMMAND_METHODS.include?(lookup) @command_flags |= 1 << i end