public
Last active

Convert a Ruby Integer into an Array of digits.

  • Download Gist
bench_integer_to_array.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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
##
# Looking at benchmark derivatives of:
# http://gistflow.com/posts/873-integer-to-array-of-digits-with-ruby
#
 
require 'benchmark'
require 'benchmark/ips'
 
module Test
class << self
def divmod(d)
base, last_digit = d.divmod(10)
digits = [last_digit]
 
while base > 9 do
base, last_digit = base.divmod(10)
digits = digits.insert(0, last_digit)
end
 
digits.insert(0, base)
end
 
def divmod_reverse(d)
digits = []
 
while d > 9 do
d, last_digit = d.divmod(10)
digits << last_digit
end
 
digits << d
digits.reverse
end
 
def mikdie(d)
digits = []
 
until d == 0 do
d, last_digit = d.divmod(10)
digits << last_digit
end
 
digits.reverse
end
 
def each_char_map(d)
d.to_s.each_char.map(&:to_i)
end
 
def chars_map(d)
d.to_s.chars.map(&:to_i)
end
 
def chars_map_bang(d)
d.to_s.chars.map!(&:to_i)
end
end
end
 
Benchmark.ips do |r|
N = 123_456_789_123_456_789_123_456_789
 
Test.methods(false).each do |method|
r.report(method.to_s) do
Test.send(method, N)
end
end
end
 
# >> Calculating -------------------------------------
# >> divmod 7915 i/100ms
# >> divmod_reverse 9702 i/100ms
# >> mikdie 9684 i/100ms
# >> each_char_map 9983 i/100ms
# >> chars_map 10446 i/100ms
# >> chars_map_bang 11363 i/100ms
# >> -------------------------------------------------
# >> divmod 105944.7 (±26.7%) i/s - 498645 in 5.034317s
# >> divmod_reverse 142615.2 (±41.0%) i/s - 591822 in 5.002818s
# >> mikdie 142368.9 (±40.8%) i/s - 600408 in 5.048888s
# >> each_char_map 128670.1 (±24.5%) i/s - 598980 in 5.015994s
# >> chars_map 137758.9 (±27.9%) i/s - 637206 in 5.051835s
# >> chars_map_bang 148910.0 (±23.9%) i/s - 693143 in 5.001251s

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.