Shift is your friend
This code¹:
crops.each do |c| c.calculate_status(user) end
takes 0.3 seconds to run. This code:
crops = crops.to_a while(c = crops.shift) c.calculate_status(user) end
takes 0.00001 seconds to run. Using shift lets Ruby clear that junk out of memory as soon as you leave the current iteration of your while loop. Each makes you keep it around.
Be advised.
–
¹ The calculate_status method works looks up some dozens of activerecord objects from different tables and does various calculations amongst them.
Tags: activerecord, performance, ruby
May 11th, 2012 at 1:08 pm
[...] mentioned, if you have a loop that allocates a bunch of memory tied to an object, destroying the current [...]