From dd7ed00ec4e2d26172642add35583a86e25dabe0 Mon Sep 17 00:00:00 2001 From: Watson Date: Sat, 12 Mar 2022 18:17:06 +0900 Subject: [PATCH] Use strip & empty? to detect Whitespaces 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 Benchmark.ips do |x| x.report("WhitespaceOrNothing") { token =~ WhitespaceOrNothing } x.report("strip & empty?") { token.strip.empty? } x.compare! end ``` ## Result ``` Warming up -------------------------------------- WhitespaceOrNothing 266.391k i/100ms strip & empty? 1.044M i/100ms Calculating ------------------------------------- WhitespaceOrNothing 2.705M (± 0.4%) i/s - 13.586M in 5.023453s strip & empty? 10.400M (± 1.1%) i/s - 52.182M in 5.017990s Comparison: strip & empty?: 10400286.2 i/s WhitespaceOrNothing: 2704552.3 i/s - 3.85x (± 0.00) slower ``` --- lib/liquid/block_body.rb | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/lib/liquid/block_body.rb b/lib/liquid/block_body.rb index 2921ce88..8de7f6cb 100644 --- a/lib/liquid/block_body.rb +++ b/lib/liquid/block_body.rb @@ -7,7 +7,6 @@ module Liquid LiquidTagToken = /\A\s*(\w+)\s*(.*?)\z/o FullToken = /\A#{TagStart}#{WhitespaceControl}?(\s*)(\w+)(\s*)(.*?)#{WhitespaceControl}?#{TagEnd}\z/om ContentOfVariable = /\A#{VariableStart}#{WhitespaceControl}?(.*?)#{WhitespaceControl}?#{VariableEnd}\z/om - WhitespaceOrNothing = /\A\s*\z/ TAGSTART = "{%" VARSTART = "{{" @@ -37,7 +36,7 @@ module Liquid private def parse_for_liquid_tag(tokenizer, parse_context) while (token = tokenizer.shift) - unless token.empty? || token =~ WhitespaceOrNothing + unless token.strip.empty? unless token =~ LiquidTagToken # line isn't empty but didn't match tag syntax, yield and let the # caller raise a syntax error @@ -150,7 +149,7 @@ module Liquid end parse_context.trim_whitespace = false @nodelist << token - @blank &&= !!(token =~ WhitespaceOrNothing) + @blank &&= token.strip.empty? end parse_context.line_number = tokenizer.line_number end