For javascript which one is faster?
a.unshift("new first value");
vs
for(i=a.length; i>0; i--) a[i] = a[i-1];
a[0] = "new first value";
vs
a[5] = a[4];
a[4] = a[3];
a[3] = a[2];
a[2] = a[1];
a[1] = a[0];
a[0] = "new first value";
Well, of course, assigning values by hand is unpractical.
But there would be cases that your array has very few items that you can assign it with your hand and it’s in a loop that would repeat it millions of times.
So I just included it.
Then the main question is:
- Is there any performance difference between first two cases?
- And can third one be faster than both of them
3
Answers
It depends but in general, directly assigning values by hand tends to be faster than using methods like unshift() or looping to assign values to an array. This is because direct assignment involves fewer operations and less overhead compared to shifting existing elements or iterating over the array.
Seems the manual assignment is good with a small number of items only, then
unshift
takes the place.In Firefox
splice
is the fastest:You could create a function dynamically that makes all the individual assignments, using the
Function
constructor.The bigger the array, the more dramatic the difference in running time. Here is a script that creates an array with one million entries, and the dynamic function with as many assignments (+ 1). It then calls the function once and also
unshift
Clearly
unshift
wins once the array size becomes significant. This should not come as a surprise as once the JS call ofunshift
is made, no more JS code is concerned, and the actual shifting can rely on compiled C code.