Hacker News new | past | comments | ask | show | jobs | submit login

Could someone who understands these things explain to me why flattening the declaration in the second example appears to make it 85% faster?



JavaScript 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.)


Oh. 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 :-)


In 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.


Yep, 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.


In 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.


This 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.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: