Created
October 18, 2018 13:17
-
-
Save rhymes/ec36c8b8c7f544570a2c23562755cdf4 to your computer and use it in GitHub Desktop.
Benchmark removal of the first character
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ruby 2.6.1 results: