Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript perf to clean an array

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?

like image 247
Vadorequest Avatar asked Feb 26 '14 16:02

Vadorequest


People also ask

How do you clear an array in JavaScript?

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.

Can we delete array element 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.


1 Answers

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.

Detailed ResultsBar Graph

like image 155
wizulus Avatar answered Nov 09 '22 01:11

wizulus