Since closures are so great, I should use them whenever possible, right?

A colleague of mine asked me this question this week and I thought that it would be a nice topic for a post. Don’t worry, I’ll be really quick about it!

Instead of saying no, I told him: it depends. “Depends on what?”, you ask. Well, one of the problem with closures is that it slows down your code. It’s relatively easy to understand why: closures also change the scope chain and that means more work for interpreter.

Besides that, closures have also been cataloged as one of the primary ways of leaking memory. The IE blog has an nice article on it, so I’ll simply redirect you to it. Notice that closures are not always bad (for instance, they allow several advanced scenarios – ex.: private fields in JavaScript). However, if you’re thinking in performance, you should probably try to reduce them to a minimum.

Btw, don’t just start removing closures if the app’s performance doesn’t match your expectations. Before doing that, you need to measure things (if you’re using lots of closures,you might start by measuring the time that operations which involve those closures take). Without that info,you’re not really sure on why something is taking lots of time.


~ by Luis Abreu on September 22, 2009.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: