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 |
This comment has been minimized.
This comment has been minimized.
this is slightly faster than my previous snippet, but it's still slower than your original
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
curious, I tried to rewrite
int_pal?
like thisexpecting it to get faster (at least with huge numbers...) but even benchmarking between
10000000...20000000
didn't show an improvement