-
Notifications
You must be signed in to change notification settings - Fork 0
/
strip_squeeze_gsub.rb
executable file
·38 lines (30 loc) · 1.01 KB
/
strip_squeeze_gsub.rb
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
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/env ruby
require 'benchmark'
# Make sure you `gem install benchmark-ips`
require 'benchmark/ips'
REGEXP_MAP = {
'gsub \\s+' => /\s+/, # https://regexper.com/#%2F%5Cs%2B%2F <= more permissive but sometimes faster
'gsub {2,}' => /\s{2,}/, # https://regexper.com/#%2F%5Cs%7B2%2C%7D%2F
'gsub \\s\\s+' => /\s\s+/ # https://regexper.com/#%2F%5Cs%5Cs%2B%2F
}
STRINGS = 6.times.collect do |i|
num_spaces = 2 ** i
string = "#{' ' * num_spaces}#{num_spaces}#{' ' * num_spaces}"
# gsub is much slower ~ 11x
# strip is better until the number of spaces gets high
benchmark_lambda = lambda do |x|
x.report("#{num_spaces} strip") do
string.strip
end
x.report("#{num_spaces} squeeze") do
string.squeeze(' '.freeze)
end
REGEXP_MAP.each do |name, regexp|
x.report("#{num_spaces} #{name}") do
string.gsub(regexp, ' '.freeze)
end
end
x.compare! # uncomment if you want comparisons between them all
end
Benchmark.ips(&benchmark_lambda)
end