Instantly share code, notes, and snippets.

Embed
What would you like to do?
string vs integer palindrome benchmarks
require 'benchmark'
def int_pal?(num)
n = num
reverse = 0
while (num > 0)
dig = num % 10
reverse = reverse * 10 + dig
num = num / 10
end
return n == reverse
end
def string_pal?(num)
s = num.to_s
s == s.reverse
end
Benchmark.bmbm do |bm|
bm.report("Integer palindrome method"){ (1...10000000).each{|x| int_pal?(x)} }
bm.report("String palindrome method"){ (1...10000000).each{|x| string_pal?(x)} }
end
=begin
Rehearsal -------------------------------------------------------------
Integer palindrome method 7.700000 0.000000 7.700000 ( 7.705190)
String palindrome method 4.890000 0.010000 4.900000 ( 4.907374)
--------------------------------------------------- total: 12.600000sec
user system total real
Integer palindrome method 7.770000 0.000000 7.770000 ( 7.773088)
String palindrome method 4.720000 0.010000 4.730000 ( 4.726223)
=end
@berdario

This comment has been minimized.

berdario commented Apr 21, 2013

curious, I tried to rewrite int_pal? like this

def int_pal?(num)
  size = (Math.log10 num).floor
  (0..(size/2.0).ceil).each do |n|
    pow1, pow2 = 10**n, 10**(size-n)
    if num / pow1 % 10 != num / pow2 % 10
      return false
    end
  end
  return true
end

expecting it to get faster (at least with huge numbers...) but even benchmarking between 10000000...20000000 didn't show an improvement

@berdario

This comment has been minimized.

berdario commented Apr 21, 2013

this is slightly faster than my previous snippet, but it's still slower than your original int_pal?

def int_pal?(num)
  size = (Math.log10 num).floor
  pow1, pow2 = 1, 10**size
  (size/2.0).ceil.times do
    if num / pow1 % 10 != num / pow2 % 10
      return false
    end
    pow1 *= 10
    pow2 /= 10
  end
  return true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment