slim-template / slim

Slim is a template language whose goal is to reduce the syntax to the essential parts without becoming cryptic.
https://slim-template.github.io
MIT License
5.29k stars 500 forks source link

Use tr() instead of gsub() to improve performance #922

Closed czj closed 1 year ago

czj commented 1 year ago

When no replacement is needed, tr() is as fast as gsub() When a replacement happens, gsub() is many times slower.

Benchmark

Source

# frozen_string_literal: true

require 'benchmark'

string_no_underscore = 'disabled'
string_one_underscore = 'data_turbo'
string_two_underscores = 'data_turbo_frame'

n = 1_000_000

puts ''
puts 'String with no underscore'
puts ''

Benchmark.bmbm do |x|
  x.report('tr:') { n.times { string_no_underscore.tr('_', '-') } }
  x.report('gsub:') { n.times { string_no_underscore.gsub('_', '-') } }
end

puts ''
puts 'String with on _underscore'
puts ''

Benchmark.bmbm do |x|
  x.report('tr:') { n.times { string_one_underscore.tr('_', '-') } }
  x.report('gsub:') { n.times { string_one_underscore.gsub('_', '-') } }
end

puts ''
puts 'String with tw _underscores'
puts ''

Benchmark.bmbm do |x|
  x.report('tr:') { n.times { string_two_underscores.tr('_', '-') } }
  x.report('gsub:') { n.times { string_two_underscores.gsub('_', '-') } }
end

Results

String with no underscore

Rehearsal -----------------------------------------
tr:     0.077771   0.002576   0.080347 (  0.080348)
gsub:   0.078601   0.002561   0.081162 (  0.081167)
-------------------------------- total: 0.161509sec

            user     system      total        real
tr:     0.077929   0.002875   0.080804 (  0.080843)
gsub:   0.078280   0.002716   0.080996 (  0.081017)

String with on _underscore

Rehearsal -----------------------------------------
tr:     0.082409   0.001873   0.084282 (  0.084294)
gsub:   0.192463   0.005014   0.197477 (  0.197483)
-------------------------------- total: 0.281759sec

            user     system      total        real
tr:     0.083051   0.002703   0.085754 (  0.085761)
gsub:   0.193000   0.005201   0.198201 (  0.198208)

String with tw _underscores

Rehearsal -----------------------------------------
tr:     0.086655   0.002528   0.089183 (  0.089183)
gsub:   0.239162   0.005984   0.245146 (  0.245157)
-------------------------------- total: 0.334329sec

            user     system      total        real
tr:     0.086596   0.002791   0.089387 (  0.089392)
gsub:   0.241907   0.006619   0.248526 (  0.248530)