Last active
December 16, 2015 07:49
-
-
Save clifff/5401367 to your computer and use it in GitHub Desktop.
string vs integer palindrome benchmarks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this is slightly faster than my previous snippet, but it's still slower than your original
int_pal?