Created
June 22, 2011 22:15
-
-
Save JoshCheek/1041393 to your computer and use it in GitHub Desktop.
Integer#digits speed
This file contains 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
def time | |
start_time = Time.now | |
1000.times { yield } | |
Time.now - start_time | |
end | |
class Integer | |
def digits | |
working_int, digits = self, Array.new | |
until working_int.zero? | |
digits.unshift working_int % 10 | |
working_int /= 10 | |
end | |
digits | |
end | |
end | |
# For Fixnum | |
time { 12345.to_s.split(//).map(&:to_i) } # => 0.009108 | |
time { 12345.to_s.split(//).map!(&:to_i) } # => 0.008999 | |
time { 12345.to_s.scan(/./).map!(&:to_i) } # => 0.006667 | |
time { 12345.to_s.each_char.map(&:to_i) } # => 0.003874 | |
time { 12345.digits } # => 0.001884 | |
# For Bignum | |
num = 107150860718626732094842504906000181056140481170 | |
time { num.to_s.split(//).map(&:to_i) } # => 0.047821 | |
time { num.to_s.split(//).map!(&:to_i) } # => 0.045045 | |
time { num.to_s.scan(/./).map!(&:to_i) } # => 0.034497 | |
time { num.to_s.each_char.map(&:to_i) } # => 0.019096 | |
time { num.digits } # => 0.03735 | |
ENV['RUBY_VERSION'] # => "ruby-1.9.2-p180" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment