5 ms·
Could someone who understands these things explain to me why flattening the declaration in the second example appears to make it 85% faster?
by seldo 13y ago
Could someone who understands these things explain to me why flattening the declaration in the second example appears to make it 85% faster?
- Zikes 13y agoIn the first example the genPrimes function is being created 2e4 times, once for each iteration of the loop. In the second example it's defined once.
- lewispollard 13y agoYep, if you use jshint/lint it'll warn you about creating functions within a loop. The performance difference is more to do with that than any inherent flaws in using anonymous functions as callbacks.
- why-el 13y agoThis is in general a good advice for most languages; instead of calling a function multiple times, do it once (and potentially store the result if you want it for later use). A similar, albeit far more simple, example would be calling a length method when iterating over an array instead of saving it to a variable.
- marijn 13y agoJavaScript functions have identity, so creating anonymous functions, even if they don't close over anything, actually requires a garbage-collected object to be allocated, rather than just creating a pointer to a piece of code. Doing this in inner loops is going to cause a noticeable performance degradation. (Doing it in expensive asynchronous operations, which is what callbacks are often used for, is not going to make a measurable difference.)
- seldo 13y agoOh. I was expecting it to be some javascript-y reason rather than a mere big-O calculation :-P Forgive me, I flew cross-country overnight and am operating on not much sleep :-)
- munificent 13y agoIn the first example, he creates a unique closure per point instance and places it on the point itself. In the second example, he creates a single closure and places it on the point's prototype. Unsurprisingly, creating one object is faster than creating a thousand of them. I'm not sure why the author thinks this has anything to do with closures.