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

Is there actually a performance hit, though? Smells like premature optimisation to be worrying about this over readable code until you’ve profiled the actual effects.



yes, there is a performance hit.

In this case, the code size is about the same if you run as-is (if you're doing DOM manipulation, performance is likely a real concern). I'd agree it would be premature optimization if we were talking about moving from a map to a full-blown loop or something, but it's hardly a huge change.

Another great example is chaining myarr.filter().filter().map().map() or some such that I sometimes see. Lodash shortcuts normal map with the assumption of arrays without holes and then uses their own iterators to avoid multiple copies. This results in a huge performance boost.

A final consideration here is transpiling. The above methods would actually increase the code size quite a bit trying to work around any edge cases and hit performance even more.

"Premature Optimization" is always a matter of opinion. Some people might consider implementing quicksort instead of bubble sort to be a premature optimization. Others might disagree with me and believe that you should always use loops instead of forEach or map. In any case, this is hardly the only case for using call/apply.


Obviously there is a performance hit, my point is whether that hit is noteworthy at all. JavaScript VMs are incredibly efficient and have all manner of optimisations that aren’t apparent at first sight. Absent profiling data we can’t know and any best practises are really just shooting in the dark. For example: is Array.prototype.map just as efficient on non-arrays? What does it do internally, do we know it doesn’t create an array anyway?




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

Search: