mirror of
https://github.com/Shopify/liquid.git
synced 2026-09-15 08:50:45 -07:00
Use start_with? and end_with? to detect SQUARE_BRAKET
## 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
```
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user