Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is variable allocation really expensive in Ruby, or does it optimize chained string methods?

I have the following method that I wrote for Project Euler - Problem 36. All it does is add up all the numbers less than 1,000,000 that are palindromes in both base 10 and base 2.

def problem_36
  (1...1_000_000).select do |n|
    n.to_s == n.to_s.reverse && n.to_s(2) == n.to_s(2).reverse
  end
end

Now, this works and gives the correct result in just over 1 second. I wanted to get it under 1 second, so I decided I would reduce the number of times I was converting numbers to strings. So I made the following changes:

def problem_36
  (1...1_000_000).select do |n|
    base10 = n.to_s
    base2  = n.to_s(2)
    base10 == base10.reverse && base2 == base2.reverse
  end
end

The trouble is, this version actually runs about 50% slower than the original. So the question is this: is it really that slow to allocate those two variables? Or is Ruby optimizing the chained method calls?

like image 828
Harry Steinhilber Avatar asked May 04 '11 16:05

Harry Steinhilber


1 Answers

In this line

n.to_s == n.to_s.reverse && n.to_s(2) == n.to_s(2).reverse

the second part is not executed if the first part is false (Ruby's && operator short-circuits, unlike its & counterpart). That saves a lot of calls to to_s(2).

like image 75
steenslag Avatar answered Nov 02 '22 07:11

steenslag