From: Chuck Remes Date: 2011-07-30T06:48:59+09:00 Subject: avoiding capturing local variables in closures I do a lot of event-driven programming (Eventmachine, ZMQMachine). You would think that by now I would know how to answer this question but I'm a bit stumped. I have a memory leak in a program. I am 80% sure that the leak is due to a long-lived block having captured a local variable (containing a *lot* of data). I would like to prevent this from happening, but I'm unsure of the best way to accomplish it. I've read Ola Bini's blog article on this topic [1]. However, I'm still a bit unclear on the concept. An example... def some_callback(bigarg1, bigarg2) foo = transform(bigarg1) bar = transformagain(bigarg2) schedule_for_execution { baz(foo, bar) } end If I am understanding things correctly, the block passed to #schedule_for_execution is capturing the variables foo, bar, bigarg1 and bigarg2. I could avoid capturing bigarg1 and bigarg2 with a small refactoring. def some_callback(bigarg1, bigarg2) foo = transform(bigarg1) bar = transformagain(bigarg2) avoid_capture(foo, bar) end def avoid_capture(foo, bar) schedule_for_execution { baz(foo, bar) } end Is this sufficient to avoid capturing those args in the closure? If not, what do I need to do? Further, what if I have an instance var that is referencing some large data? Do I need to worry about that being captured by the block or does it not matter because the block has already captured self? e.g. def some_callback(bigarg1, bigarg2) foo = transform(bigarg1) bar = transformagain(bigarg2) @quxxo = bigarg1 + bigarg2 schedule_for_execution { baz(foo, bar) } end cr [1] http://ola-bini.blogspot.com/2007/12/ruby-closures-and-memory-usage.html