phlex-ruby / phlex

A framework for building object-oriented views in Ruby.
https://beta.phlex.fun
MIT License
1.28k stars 83 forks source link

Prefer `delete` to `tr` when using it to remove characters from a string #714

Closed willcosgrove closed 6 months ago

willcosgrove commented 6 months ago

After doing some benchmarking, it looks like delete is about 19% faster than tr when removing characters from a string.

test_string = "this is the test string"

Benchmark.ips do |x|
  x.report("tr") do
    test_string.tr(" ", "")
  end

  x.report("delete") do
    test_string.delete(" ")
  end
end
Calculating -------------------------------------
          tr      6.367M (± 3.4%) i/s -     31.997M in   5.032180s
      delete      7.567M (± 6.0%) i/s -     38.022M in   5.053830s

Comparison:
      delete:  7566538.8 i/s
          tr:  6366671.2 i/s - 1.19x  slower
joeldrapper commented 6 months ago

Nice. I ran the browser tests and we're still good.