4 ms·
As always, munificent is right on the money. The "closure pattern" is one of the most serious JavaScript anti-patterns -- it doesn't make much of a difference
by jashkenas 16y ago
As always, munificent is right on the money.
The "closure pattern" is one of the most serious JavaScript anti-patterns -- it doesn't make much of a difference in tiny scripts, but for any decent-size JavaScript application, it can hurt performance terribly, especially regarding memory use.
For example, benchmarking the creation of 1 million objects, each with 10 member functions, in both the prototypal style and the closure style (in Chrome):
1 million prototypal objects: Brief pause, 32.4 MB
1 million closure objects: Minutes wait, 368.1 MB
If you're doing object-oriented code in JS, please use the "prototype" property, like the language is designed to do.
For more info, here's Brendan Eich on the subject:
http://www.aminutewithbrendan.com/pages/20110216 http://www.aminutewithbrendan.com/pages/20110216
- nxn 16y agoI don't even know if this can be considered the "closure" pattern anymore, but I wanted to try to get method sharing among the objects by doing something like this: https://gist.github.com/877259 https://gist.github.com/877259 The hope was that since the functions were created and bound within the function literal, the "create" method could simply assign references to the existing functions instead of creating a new function each time (ie, avoid what munificent mentioned). Funny thing is, even though the last line indicates that the first and last objects' "ten" method is actually shared between them, I'm still getting about 370 MB of memory usage after creating 1 million objects. I am under assumption that the cause of this memory increase is the fact that each one of the million objects has its own local references to each of the 10 functions. When I put the 10 functions inside of the "create" method, memory usage goes up again to roughly 750 MB.
- jimmydo 16y agoThat was a really interesting talk--thanks for the link! Something that initially confused me was that Eich's use of the term "prototypal" (a pattern for implementing class-based inheritance) was different from Douglas Crockford's use of it (an alternative to class-based inheritance - http://javascript.crockford.com/prototypal.html http://javascript.crockford.com/prototypal.html). In case anyone else finds this useful, here's how I sorted it out: - "class-based" & "prototype-based" inheritance (Crockford refers to them as "classical" & "prototypal" inheritance). Different styles of instantiating objects. - "closure pattern" & "prototypal pattern" (aka "prototypal inheritance" in this context). Different techniques for implementing class-based inheritance.