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: , ,

One Response to “Shift is your friend”

  1. Erik on Rails » Blog Archive » Destructive (fast) Ruby each Says:

    [...] mentioned, if you have a loop that allocates a bunch of memory tied to an object, destroying the current [...]

Leave a Reply