Javascript array size and performance
Every Javascript tutorial on arrays says make your arrays with var array_name = []; unless you have all the values at the start and can do it explicitly.
Additionally if you read up on fast loop performance you're told to do:
var i = number_of_interations;
while(--i)
{
//do stuff
}
Put this together and the way to fill a large array is apparently to do:
var i = planned_array_size;
var array_name = [];
while (--i)
{
array_name[i] = insert_value_or_function_call_here;
}
I've spent a bit of time recently looking at the comparative Javascript performance of JavascriptCore (Safari), SpiderMonkey (Firefox) and V8 (Chrome).
One thing that stood out to me was a test where SpiderMonkey and V8 destroyed JavascriptCore by a factor of almost 100, the test was meant to be about Math.trunc performance vs bitwise operators but Safari just performed like a dog in all cases. The test's preparation code was using the above syntax to fill a loop with random numbers then in the test was looping through the array flooring them and adding them up.
I found that if I changed the preparation code to loop forwards suddenly safari scored highest, changing it to set the array size with the array constructor advance made it perform even better. Notably this changes improved performance in all browsers though Safari in particular went to the top.
Conclusions:
Primary: you don't want to dynamically resize arrays backwards it kills performance; use the Array Constructor to size it
Secondary: Safari's JS engine is crazy fast when it's not dynamically resizing (as in it curb stomps V8 in a lot of tests I've been doing)
Try running this in a couple of browsers then consider bringing back that array constructor
:
https://jsperf.com/array-creations/1
(I note that those tests only show creation speeds, it was access speeds that pointed me to the issue, for those try out these two test pages and compare - I note the differences here are smaller except in Safari:
https://jsperf.com/or-vs-floor/43
https://jsperf.com/trun-vs-or