【发布时间】: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() 真的比其他测试快得多吗?测试中是否存在我没有看到的缺陷?
【问题讨论】:
-
你的测试有缺陷。它主要在空数组上运行。在这种情况下,while 条件比方法调用更快。
-
好吧,@Aaditmshah 被他自己的测试结果骗了……
-
数组怎么是空的?
标签: javascript arrays performance performance-testing