【发布时间】:2016-09-28 21:17:55
【问题描述】:
在迭代所有元素时,什么会更快?
方法一:
let array = [10, 0, 0, 20, 1, 0, 12, 2, 0];
for(let i = 0, l = array.length; i < l; i += 3) {
doSomething(array[i], array[i + 1], array[i + 2]);
}
对
方法二:
let array = [{id:10, x:0, y:0}, {id:20, x:1, y:0}, {id:12, x:2, y:0}];
for(let i = 0, l = array.length, current = null; i < l; ++i) {
current = array[i];
doSomething(current.id, current.x, current.y);
// i'm aware that we could make doSomething work with the object
// -> even a thing to consider?
}
我的猜测是我们使用 1 会更快,但是你们可能拥有更多的 v8、spidermonkey 等英特尔,所以最终对象处理和较小的数组可能会更快?
【问题讨论】:
-
您为什么不使用
Date.now()自己看看? -
方法 1 应该更快,但方法 2 是组织您正在使用的数据的更好方法。
-
我不认为以这种或那种方式访问对象属性在 2016 年会产生重大变化。我希望两者在性能方面做同样的事情。
-
你为什么这么问?最好的猜测是差异可能非常小,您很可能过度优化
-
您可以使用Performance.now()自行查看
标签: javascript arrays performance object