最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript perf to clean an array - Stack Overflow

programmeradmin1浏览0评论

I just took a look to that:

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./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?

Share Improve this question asked Feb 26, 2014 at 16:33 VadorequestVadorequest 18.1k27 gold badges129 silver badges231 bronze badges 5
  • 3 Have a look at stackoverflow./a/1234337/2674883 – Nicolae Olariu Commented Feb 26, 2014 at 16:37
  • 3 Thanks! But the links doesn't explains why it's faster, or I missed something? – Vadorequest Commented Feb 26, 2014 at 16:41
  • 3 A lot is going on when length is set: es5.github.io/#x15.4.5.1, pared to .shift: 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 Commented Feb 26, 2014 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 Commented Feb 26, 2014 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 Commented Mar 14, 2014 at 17:27
Add a ment  | 

2 Answers 2

Reset to default 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./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.

发布评论

评论列表(0)

  1. 暂无评论