12

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?

Vadorequest
  • 16,593
  • 24
  • 118
  • 215
  • 3
    Have a look at http://stackoverflow.com/a/1234337/2674883 – Nicolae Olariu Feb 26 '14 at 16:37
  • 3
    Thanks! But the links doesn't explains why it's faster, or I missed something? – Vadorequest Feb 26 '14 at 16:41
  • 3
    A lot is going on when `length` is set: http://es5.github.io/#x15.4.5.1, compared to `.shift`: http://es5.github.io/#x15.4.4.9. Still trying to find out which part of each algorithm is triggered when `.length = 0` is executed. – Felix Kling Feb 26 '14 at 16:48
  • 1
    Mmh. Still no idea. It looks like `.shift` also triggers the same code that assigning to `.length` would trigger. – Felix Kling Feb 26 '14 at 16:54
  • It must be the garbage collection mechanism and possibly some other iterative conditional check that is employed in the interpreter. Which method is performs the best is dependent on the Javascript engine. In Firefox the pop method is 1.8%+ faster than the shift method. – David H. Bennett Mar 14 '14 at 17:27

2 Answers2

14

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 Results Bar Graph

wizulus
  • 5,653
  • 2
  • 23
  • 40
  • 3
    Ahhh, I knew something was wrong here. Or that I missed something mportant about javascript arrays, thanks! How a loop could be faster than a simple assignation, except with magic that triggers hidden stuff in background I don't see how that could have ben possible. – Vadorequest Feb 26 '14 at 20:30
2

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.

Gil
  • 1,794
  • 1
  • 12
  • 18