Skip to content

Instantly share code, notes, and snippets.

@rhymes
Created October 18, 2018 13:17
Show Gist options
  • Save rhymes/ec36c8b8c7f544570a2c23562755cdf4 to your computer and use it in GitHub Desktop.
Save rhymes/ec36c8b8c7f544570a2c23562755cdf4 to your computer and use it in GitHub Desktop.
Benchmark removal of the first character
# from https://stackoverflow.com/a/3614592/4186181
require 'benchmark'
N = 1_000_000
class String
def eat!(how_many = 1)
self.replace self[how_many..-1]
end
def first(how_many = 1)
self[0...how_many]
end
def shift(how_many = 1)
shifted = first(how_many)
self.replace self[how_many..-1]
shifted
end
alias_method :shift!, :shift
end
class Array
def eat!(how_many = 1)
self.replace self[how_many..-1]
end
end
puts RUBY_VERSION
STR = "[12,23,987,43"
Benchmark.bm(7) do |b|
b.report('[0]') { N.times { "[12,23,987,43"[0] = '' } }
b.report('[/^./]') { N.times { "[12,23,987,43"[/^./] = '' } }
b.report('[/^\[/]') { N.times { "[12,23,987,43"[/^\[/] = '' } }
b.report('sub+') { N.times { "[12,23,987,43".sub(/^\[+/, "") } }
b.report('sub') { N.times { "[12,23,987,43".sub(/^\[/, "") } }
b.report('gsub') { N.times { "[12,23,987,43".gsub(/^\[/, "") } }
b.report('[1..-1]') { N.times { "[12,23,987,43"[1..-1] } }
b.report('slice') { N.times { "[12,23,987,43".slice!(0) } }
b.report('length') { N.times { "[12,23,987,43"[1..STR.length] } }
b.report('eat!') { N.times { "[12,23,987,43".eat! } }
b.report('reverse') { N.times { "[12,23,987,43".reverse.chop.reverse } }
end
@rhymes
Copy link
Author

rhymes commented Mar 13, 2019

Ruby 2.6.1 results:

              user     system      total        real
[0]       0.218845   0.001119   0.219964 (  0.221109)
[/^./]    0.449671   0.002063   0.451734 (  0.454120)
[/^\[/]   0.482946   0.002187   0.485133 (  0.487219)
sub+      0.567491   0.002452   0.569943 (  0.572406)
sub       0.575813   0.006107   0.581920 (  0.587296)
gsub      2.438294   0.011321   2.449615 (  2.460864)
[1..-1]   0.259654   0.001290   0.260944 (  0.262560)
slice     0.357238   0.001486   0.358724 (  0.360263)
length    0.430018   0.003040   0.433058 (  0.437614)
eat!      0.502541   0.005859   0.508400 (  0.514503)
reverse   0.464882   0.002390   0.467272 (  0.469595)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment