Skip to content

Instantly share code, notes, and snippets.

@halilim
Last active November 19, 2015 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halilim/f9e2b53d5be6032a09cb to your computer and use it in GitHub Desktop.
Save halilim/f9e2b53d5be6032a09cb to your computer and use it in GitHub Desktop.
Benchmark various digitization methods

Results

(Median-ish values after 3 runs)

modulus:   479251.0 i/s
unshift:   428200.9 i/s - 1.12x slower
 divmod:   354892.0 i/s - 1.35x slower
    log:   227779.9 i/s - 2.10x slower
 string:   212474.5 i/s - 2.26x slower
require 'benchmark/ips'
def digits_s(n)
n.to_s.chars.map(&:to_i)
end
# http://stackoverflow.com/a/12909952/372654
def digits_divmod(n)
n = n.abs
[].tap do |result|
while n > 0
n, digit = n.divmod 10
result.unshift digit
end
end
end
# http://stackoverflow.com/a/13091613/372654
# This is kind of the manual version of divmod - Halil Özgür
def digits_modulus(i)
[].tap do |result|
while i > 0
digit = i % 10
i /= 10
result.unshift digit
end
end
end
# http://stackoverflow.com/a/12908181/372654
def digits_log(n)
Math.log10(n).floor.downto(0).map { |i| (n / 10**i) % 10 }
end
# http://stackoverflow.com/a/13092348/372654
def digits_unshift(x, y=[])
x < 10 ? y.unshift(x) : digits_unshift(x/10, y.unshift(x%10))
end
Benchmark.ips do |x|
x.report('string') { digits_s(rand(1000000000)) }
x.report('divmod') { digits_divmod(rand(1000000000)) }
x.report('modulus') { digits_modulus(rand(1000000000)) }
x.report('log') { digits_log(rand(1000000000)) }
x.report('unshift') { digits_unshift(rand(1000000000)) }
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment