I just took a look to that:
http://jsperf.com/array-destroy/32
I don't understand how the first one:
arr.length = 0;
Can be slower than:
while (arr.length > 0) {
arr.shift();
}
Someone could link/explain why?
I just took a look to that:
http://jsperf.com/array-destroy/32
I don't understand how the first one:
arr.length = 0;
Can be slower than:
while (arr.length > 0) {
arr.shift();
}
Someone could link/explain why?
In the test setup, a large array is created. Once the test begins, the array is emptied, and the test repeats itself. However, every time after the first run of the test, the array is already empty. To perform this test accurately, you have to create a new array each time. Try this:
http://jsperf.com/array-destroy/67
I modified the test to return a new array each time. The results are as expected. splice
and length
are fastest because they instantly modify the length of the array without a loop.
When using pop()
the last element in an array is removed and that's it.
When using shift()
, the first array is removed and all the rest of the elements are re-indexed. The bigger the array, the longer this will take.