javascript 从vs for循环遍历类数组对象

yuvru6vn  于 2023-08-02  发布在  Java
关注(0)|答案(3)|浏览(160)

对于遍历类似数组的对象,使用Array.from( ).forEach()还是for循环更好?
类似数组的对象示例:

  1. let childeNodes = document.querySelector('#someid').childNodes;

字符串
使用Array.from().forEach()迭代:

  1. Array.from(childNodes).forEach(node => {
  2. // do something with node
  3. })


或者使用for进行迭代:

  1. for (let i = 0; i < childNodes.length; i++) {
  2. // do something with childNodes[i]
  3. }

0qx6xfy6

0qx6xfy61#

请注意,还有两个更有趣的变体:

  1. Array.from函数接受第二个参数,该参数是为每个元素调用的回调函数。我们可以预期它比附加到它的.forEach方法更快,因为不需要创建中间数组
  2. ES6 for..of循环
    但众所周知的事实是,老式的for循环击败了所有替代方案。这里是一个小片段,使测量:
  1. const childNodes = document.querySelector('#someid').childNodes;
  2. let i, start, duration, times = 500000;
  3. k = times;
  4. start = performance.now();
  5. while (k>0) {
  6. Array.from(childNodes).forEach(node =>
  7. k -= node ? 1 : 0
  8. );
  9. }
  10. duration = performance.now() - start;
  11. console.log('Array.from with forEach: ', duration.toFixed(2));
  12. k = times;
  13. start = performance.now();
  14. while (k>0) {
  15. Array.from(childNodes, node =>
  16. k -= node ? 1 : 0
  17. );
  18. }
  19. duration = performance.now() - start;
  20. console.log('Array.from callback: ', duration.toFixed(2));
  21. k = times;
  22. start = performance.now();
  23. while (k>0) {
  24. for (let i = 0; i < childNodes.length; i++) {
  25. k -= childNodes[i] ? 1 : 0;
  26. }
  27. }
  28. duration = performance.now() - start;
  29. console.log('Oldfashioned for-loop: ', duration.toFixed(2));
  30. k = times;
  31. start = performance.now();
  32. while (k>0) {
  33. for (const node of childNodes) {
  34. k -= node ? 1 : 0;
  35. }
  36. }
  37. duration = performance.now() - start;
  38. console.log('for-of loop: ', duration.toFixed(2));

个字符

展开查看全部
50pmv0ei

50pmv0ei2#

你的问题用词不对。
而不是:Array.from vs for(..)应该是:Array.forEachfor(...)
对于这个问题,你可以在SO或简单的谷歌搜索中找到非常好的答案。

tl;dr;

for循环更快。forEach较慢,但更适合函数式编程范例。

nnt7mjpx

nnt7mjpx3#

根据这个jsperffor循环比forEach快,但for...in最慢。
正如前面提到的,Array.from是不相关的,因为它只被调用一次。
另外值得一提的是,在您的示例的真实的用例中,最慢的操作可能是document.querySelector。根据这个jsperf使用getElementById要快得多。
这里更大的收获是在担心性能之前理解用例和可维护性;当你担心性能的时候,更全面地考虑它。

相关问题