Array.pop()在循环中的确比Array.length =快50倍

jdp*_*nix 3 javascript arrays performance performance-testing

我的问题是由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';
  }

};
Run Code Online (Sandbox Code Playgroud)

测试:

// 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();
Run Code Online (Sandbox Code Playgroud)

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

这里发生了什么?是Array.pop()在一个循环实际上这远远超过其他测试更快吗?我没有看到测试中存在缺陷吗?

Ber*_*rgi 6

JsPerf每次设置多次运行每个测试.这意味着您只对10000个元素的数组进行一次测试,并且在随后的(很多)运行中只有100个项目留在数组中.

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

一个正确的测试用例,就像@zerkms创建的那样,在每次迭代时都会使用一个新数组 - 这就是你要测试的东西.随着更多(类似)工作的完成,解决方案之间的相对差异会变小,但您仍然可以注意到趋势.
哦,当然,即使这些仍然是编译器优化的牺牲品,所以你永远不能确定......