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
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.
- 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.
- It's wasteful, bad code and makes it more likely you'll introduce a memory leak.
- 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.
- See: common sense
§