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?
There are various methods to empty an array in JavaScript. Assigning the array to an empty array is the quickest method of emptying an array in JavaScript. In javascript, length is a property that, when set to 0, clears the array. splice() method can be used to delete 1 or more elements from the array in JavaScript.
Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With