简体   繁体   English

for-for循环的性能成本

[英]Performance cost of the for-of loop

Recently I was experimenting with ES6 code using babel . 最近,我正在使用babel尝试ES6代码。 I was quite surprised to see the verbose code of a compiled for of loop. 我很惊讶地看到for循环的已编译代码。 Here is an example: 这是一个例子:

ES6 ES6

const a = [1, 2, 3, 4, 5];
for (const i of a)
{
    console.log(i);
}

Compiled 已编译

"use strict";
var a = [1, 2, 3, 4, 5];
for (
    var _iterator = a,
    _isArray = Array.isArray(_iterator),
    _i = 0,
    _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();
  ;

) {
      var _ref;

      if (_isArray) {
          if (_i >= _iterator.length) break;
              _ref = _iterator[_i++];
          } else {
              _i = _iterator.next();
              if (_i.done) break;
                  _ref = _i.value;
      }

      var i = _ref;

      console.log(i);
}

Whereas standard for loops, or a .forEach loop look almost exactly the same compiled as they do in ES6. 标准的for循环或.forEach循环看起来与ES6中的编译几乎完全相同。 I use the for of loop quite a lot in my code, it is a nice concise way to iterate over arrays. 我在代码中大量使用了for of循环,这是一种遍历数组的简洁方法。 But until now I was unaware of all the added state and logic this brings with it. 但是直到现在,我还没有意识到随之而来的所有附加状态和逻辑。 I would like to know whether using this compared to a normal for loop or .forEach has a non-negligible performance cost? 我想知道与普通的for循环或.forEach相比,此方法的性能成本是不可忽略的吗?

I would like to know whether using this compared to a normal for loop or .forEach has a non-negligible performance cost? 我想知道与普通的for循环或.forEach相比,此方法的性能成本是不可忽略的吗?

That completely depends on the size of your array. 这完全取决于数组的大小。

Unless you're iterating over millions of elements, you're not going to notice a difference. 除非您要遍历数百万个元素,否则您不会注意到它们之间的差异。

Babel expands the loop this much for compatibility purposes. Babel出于兼容性目的极大地扩展了循环。 Older browsers don't have for...of , but the functionality can be reproduced like that. 较旧的浏览器没有for...of ,但是可以像这样复制功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM