Skip to content

Instantly share code, notes, and snippets.

@clifff
Last active December 16, 2015 07:49
Show Gist options
  • Save clifff/5401367 to your computer and use it in GitHub Desktop.
Save clifff/5401367 to your computer and use it in GitHub Desktop.
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
Copy link

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