在像javascript中的对象这样的数组更好用,性能,Array.from或for循环?
示例:
let childeNodes = document.querySelector('#someid').childNodes;
Array.from(childNodes).forEach(node => {
// do something with node
})
// or
for (let i = 0; i < childNodes.length; i++) {
// do something with childNodes[i]
}
答案 0 :(得分:1)
请注意,还有两个有趣的变体:
//*[contains(@class, 'tweet-text')][2]/text()
函数接受第二个参数,该参数是为每个元素调用的回调。我们可以期望它比附加到它的Array.from
方法更快地工作,因为不需要创建中间数组
ES6 .forEach
循环
但众所周知,老式的for..of
循环胜过所有选择。这是一个进行测量的小片段:
for
&#13;
const childNodes = document.querySelector('#someid').childNodes;
let i, start, duration, times = 500000;
k = times;
start = performance.now();
while (k>0) {
Array.from(childNodes).forEach(node =>
k -= node ? 1 : 0
);
}
duration = performance.now() - start;
console.log('Array.from with forEach: ', duration.toFixed(2));
k = times;
start = performance.now();
while (k>0) {
Array.from(childNodes, node =>
k -= node ? 1 : 0
);
}
duration = performance.now() - start;
console.log('Array.from callback: ', duration.toFixed(2));
k = times;
start = performance.now();
while (k>0) {
for (let i = 0; i < childNodes.length; i++) {
k -= childNodes[i] ? 1 : 0;
}
}
duration = performance.now() - start;
console.log('Oldfashioned for-loop: ', duration.toFixed(2));
k = times;
start = performance.now();
while (k>0) {
for (const node of childNodes) {
k -= node ? 1 : 0;
}
}
duration = performance.now() - start;
console.log('for-of loop: ', duration.toFixed(2));
&#13;
答案 1 :(得分:0)
你的问题是错误的。
而不是:Array.from
vs for(..)
它应该是:Array.forEach
vs for(...)
对于这个问题,你可以在SO或简单的谷歌搜索中找到非常好的答案。
for
循环更快。
forEach
速度较慢,但更适合functional programming paradigms。
答案 2 :(得分:0)