【问题标题】:Is Array.pop() in a loop really 50x faster than Array.length =循环中的 Array.pop() 是否真的比 Array.length = 快 50 倍
【发布时间】:2015-01-26 02:51:25
【问题描述】:

我的问题是由 Jsperf 在这里产生的:

http://jsperf.com/the-fastest-way-to-truncate-an-array/7

设置代码:

Benchmark.prototype.setup = function() {
  var test_array = [];

  for (var j=0; j< 10000; j++){
    test_array[j] = 'AAAAAAAAAA';
  }

};

还有测试:

// Array.slice() method
result = test_array.slice(0,100);

// Array.splice() method
test_array.splice(100);

// Modifying Array.length
test_array.length = 100;

// Array.pop() method
while (test_array.length > 100) test_array.pop();

JSPerf 的结果表明,the Array.pop() 方法的完成速度比其他方法快很多——在某些实现上快了 80 倍以上。

这里发生了什么?循环中的Array.pop() 真的比其他测试快得多吗?测试中是否存在我没​​有看到的缺陷?

【问题讨论】:

标签: javascript arrays performance performance-testing


【解决方案1】:

JsPerf 每次设置都会多次运行每个测试。这意味着您只需针对 10000 个元素的数组进行一次测试,而在随后的(非常多的)运行中,数组中只剩下 100 个项目。

在这种情况下,while 循环的条件是超快的:单个的,可能是缓存的,属性访问和比较。所有其他测试用例都调用一个方法或一个 setter 方法(它只是在内部进行此测试,可能还有更多)。

一个合适的测试用例,比如the one created by @zerkms,确实在每次迭代时都使用一个新数组——这就是你想要测试的东西。随着更多(相似)工作的完成,解决方案之间的相对差异会变得更小,但您仍然可以注意到趋势。
哦,当然还有这些still fall prey to compiler optimisations,所以你永远无法确定……

【讨论】:

    猜你喜欢
    • 2019-11-16
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 2012-01-17
    • 2021-11-25
    • 2011-09-15
    • 2011-03-10
    相关资源
    最近更新 更多