public
Created

Integer#digits speed

  • Download Gist
digits.rb
Ruby
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
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"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.