【发布时间】:2018-03-09 03:30:57
【问题描述】:
我是 node.js 的新手。
我尝试在数组中插入 70000 个项目,然后将它们全部删除:
var Stopwatch = require("node-stopwatch").Stopwatch;
var stopwatch = Stopwatch.create();
var a = []
stopwatch.start();
for (var i = 1 ; i < 70000 ; i++){
a.push((parseInt(Math.random() * 10000)) + "test");
}
for (var i = 1 ; i < 70000 ; i++){
a.splice(0,1);
}
stopwatch.stop();
console.log("End: " + stopwatch.elapsedMilliseconds + " : " + a.length);
它工作正常,输出是:
PS C:\Users\Documents\VSCode> node test.js
End: 51 : 0
但是当我将项目数量增加到 72000 时,结束需要太多时间:
var Stopwatch = require("node-stopwatch").Stopwatch;
var stopwatch = Stopwatch.create();
var a = []
stopwatch.start();
for (var i = 1 ; i < 72000 ; i++){
a.push((parseInt(Math.random() * 10000)) + "test");
}
for (var i = 1 ; i < 72000 ; i++){
a.splice(0,1);
}
stopwatch.stop();
console.log("End: " + stopwatch.elapsedMilliseconds + " : " + a.length);
输出是:
End: 9554 : 0
为什么会发生?只增加了2000件,但是太费时间了。
Node.js 版本为:v6.11.3
【问题讨论】:
-
你知道时间爆炸是发生在数组的填充还是破坏,还是两者兼而有之?
-
@apsillers 在破坏中'a.splice(0,1); '
-
刚刚在调查/玩弄这个 - 对我来说上限是 71109 - 在这之后,它真的很慢。以 71110 为例,耗时 12476 毫秒! 71109 是 64 毫秒
-
查看v8 source code for arrays,我看到v8内部有两个不同的
splice操作。一种是完整的普通数组;另一个用于稀疏数组 (['foo',,,,,'bar',,,,]) 和对象。出于某种原因,v8 可能会使用其较慢的回退splice来处理更大的数组。 -
Win7x32,节点 5.11.1:在 172000 上减速。