Skip to content

Instantly share code, notes, and snippets.

@okkez
Created December 20, 2018 02:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save okkez/6e199011505c6db7e2e1003cc94f8cbc to your computer and use it in GitHub Desktop.
Save okkez/6e199011505c6db7e2e1003cc94f8cbc to your computer and use it in GitHub Desktop.
String#squeeze is faster than String#gsub
require "benchmark"
str1 = "a b"
str2 = "a b"
N = 100000
Benchmark.bmbm do |x|
x.report("gsub") do
N.times do
str1.gsub(/ +/, " ")
end
end
x.report("gsub w/o spaces") do
N.times do
str2.gsub(/ +/, " ")
end
end
x.report("squeeze") do
N.times do
str1.squeeze(" ")
end
end
x.report("squeeze w/o spaces") do
N.times do
str2.squeeze(" ")
end
end
end
$ ruby -v b.rb
ruby 2.5.3p105 (2018-10-18 revision 65156) [x86_64-linux]
Rehearsal ------------------------------------------------------
gsub 0.144169 0.000000 0.144169 ( 0.144228)
gsub w/o spaces 0.141979 0.000000 0.141979 ( 0.142020)
squeeze 0.019956 0.000000 0.019956 ( 0.019966)
squeeze w/o spaces 0.020379 0.000000 0.020379 ( 0.020383)
--------------------------------------------- total: 0.326483sec
user system total real
gsub 0.147720 0.000000 0.147720 ( 0.147767)
gsub w/o spaces 0.138309 0.000000 0.138309 ( 0.138351)
squeeze 0.019598 0.000000 0.019598 ( 0.019602)
squeeze w/o spaces 0.020238 0.000000 0.020238 ( 0.020244)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment