Hacker News new | past | comments | ask | show | jobs | submit login
JavaScript – Array Direct Assignment (suhairhassan.com)
14 points by suhair on June 2, 2013 | hide | past | favorite | 9 comments



See also this benchmark, which seems to have very different results from the scottlogic link: http://jsperf.com/array-push-vs-array-length23333/2

I just re-ran it on FF24 (nightly), and also saw results where .push beats this kludge.

So before everyone runs off and takes 'direct array assignment is fast' as a rule of thumb, please consider that it quite probably isn't.


Also faster in most versions of chrome


I prefer readable code to hacks. Unless you absolutely have a hot spot in your code that will benefit, readability should outweigh this. JavaScript engines will catch up.


after reading the underscore source I remember wondering if direct array assignment was really significantly better than calling push. here's a quick link to the perf reference made in the article: http://www.scottlogic.co.uk/2010/10/javascript-array-perform..., oddly interesting is that calling push was faster in chrome than in direct assignment. I wonder what the results would be like in newer browsers...


Direct assignment without using the calculated length property performs way ahead than others, at least in chrome http://jsperf.com/array-direct-assignment-vs-push/3


Wow, direct assignment is an order of magnitude faster than push (in my test, chrome 27 on windows 7). Can anyone explain why?


Direct assignment is the only test in which the length of array doesn't change.


this smells like a js engine optimization. you wouldn't expect substantially different machine code to run for "Direct assignment" and "other". i wouldn't be surprised if the loop is being unrolled or something.


They could all be reasonably unrolled, so it's probably something else. I expect the engine can more easily calculate the final required Array size and preallocate it upfront avoiding resize operation on each loop iteration. (which is anyway JS best practice when possible)




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

Search: