File: gsub_vs_tr_single_character.rb

package info (click to toggle)
ruby-rspec 3.13.0c0e0m0s1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,856 kB
  • sloc: ruby: 70,868; sh: 1,423; makefile: 99
file content (28 lines) | stat: -rw-r--r-- 625 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
require 'benchmark/ips'

Benchmark.ips do |x|
  y = '1_2_3_4_5_6_7_8_9_10'

  x.report('gsub') do |_times|
    y.tr('_', ' ')
  end

  x.report('tr') do |_times|
    y.tr('_', ' ')
  end

  x.compare!
end

__END__

Calculating -------------------------------------
                gsub    29.483k i/100ms
                  tr    79.170k i/100ms
-------------------------------------------------
                gsub     10.420B (±23.7%) i/s -     31.106B
                  tr     78.139B (±20.6%) i/s -    129.289B

Comparison:
                  tr: 78139428607.9 i/s
                gsub: 10419757735.7 i/s - 7.50x slower