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

Published Tue, Sep 22 2009 12:48

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.

Filed under:

Leave a Comment

If you can't read this number refresh your screen
Enter the numbers above:  


This Blog





Email Notifications


  • View Luis Abreu's profile on LinkedIn

    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover