Saturday, March 10, 2012

Caveat Scriptor: Closures

Closures are a flexible and powerful concept.  However, you have to keep in mind certain caveats when writing them.

Understand how the closure will grow
  • You can easily create a memory leak with a closure because the only interface to the allocated memory is through the closure (typically). You should make sure your closure will not grow unbounded.
Watch out for capturing references
  • This is more of standard gotcha, but it's even more important when dealing with closures. A closure will capture lexical variables including ones that contain references. This means whatever those references point to will continue stick around as long as the closure is around, unless they are explicitly weak refs.
Don't close over variables you don't need to close over
  • It's wasteful, bad code and makes it more likely you'll introduce a memory leak.
Make the functions that will become closures as simple as possible
  • The bigger, more complex the function that will become a closure, the more likely you are to have a bug which may lead to a memory leak.
Don't create closures when they aren't needed
  • See: common sense