Javascript 效率:'for' 与 'forEach'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43031988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:37:00  来源:igfitidea点击:

Javascript efficiency: 'for' vs 'forEach'

javascriptloopsfor-loopforeach

提问by tonyrobbins

What is the current standard in 2017 in Javascript with for() loops vs a .forEach.

2017 年 Javascript 中 for() 循环与 .forEach 的当前标准是什么。

I am currently working my way through Colt Steeles "Web Dev Bootcamp" on Udemy and he favours forEachover forin his teachings. I have, however, searched for various things during the exercises as part of the course work and I find more and more recommendations to use a for-loop rather than forEach. Most people seem to state the for loop is more efficient.

我目前的工作我的方式,通过柯尔特史蒂尔斯的“Web开发训练营”在Udemy他热衷forEachfor他的教导。然而,作为课程工作的一部分,我在练习期间搜索了各种内容,我发现越来越多的建议使用for-loop 而不是forEach. 大多数人似乎都说 for 循环更有效。

Is this something that has changed since the course was written (circa 2015) or are their really pros and cons for each, which one will learn with more experience.

这是自课程编写(大约 2015 年)以来发生的变化,还是它们各自的真​​正优点和缺点,随着更多的经验,人们会学到哪一个。

Any advice would be greatly appreciated.

任何建议将不胜感激。

回答by vol7ron

for

为了

forloops are much more efficient. It is a looping construct specifically designed to iterate while a condition is true, at the same time offering a stepping mechanism (generally to increase the iterator). Example:

for循环效率更高。它是一个循环结构,专门设计用于在条件为true 时进行迭代,同时提供步进机制(通常用于增加迭代器)。例子:

for (var i=0, n=arr.length; i < n; ++i ) {
   ...
}

This isn't to suggest that for-loops will always be more efficient, just that JS engines and browsers have optimized them to be so. Over the years there have been compromises as to which looping construct is more efficient (for, while, reduce, reverse-while, etc) -- different browsers and JS engines have their own implementations that offer different methodologies to produce the same results. As browsers further optimize to meet performance demands, theoretically [].forEachcould be implemented in such a way that it's faster or comparable to a for.

这并不是说for循环总是更高效,只是 JS 引擎和浏览器已经优化了它们。多年来,对于哪种循环结构更有效(for、while、reduce、reverse-while 等)一直存在妥协——不同的浏览器和 JS 引擎都有自己的实现,提供不同的方法来产生相同的结果。随着浏览器进一步优化以满足性能需求,理论上[].forEach可以以更快或与for.

Benefits:

好处:

  • efficient
  • early loop termination (honors breakand continue)
  • condition control (i<ncan be anything and not bound to an array's size)
  • variable scoping (var ileaves iavailable after the loop ends)
  • 高效的
  • 早期循环终止(荣誉breakcontinue
  • 条件控制(i<n可以是任何东西,不受数组大小的限制)
  • 变量范围(循环结束后可用的var i叶子i

forEach

为每个

.forEachare methods that primarily iterate over arrays (also over other enumerable, such as Mapand Setobjects). They are newerand provide code that is subjectively easier to read. Example:

.forEach是主要遍历数组(也遍历其他可枚举对象,例如MapSet对象)的方法。它们更新并提供主观上更易于阅读的代码。例子:

[].forEach((val, index)=>{
   ...
});

Benefits:

好处:

  • does not involve variable setup (iterates over each element of the array)
  • functions/arrow-functions scope the variable to the block
    In the example above, valwould be a parameter of the newly created function. Thus, any variables called valbefore the loop, would hold their values after it ends.
  • subjectively more maintainable as it may be easier to identify what the code is doing -- it's iterating over an enumerable; whereas a for-loop could be used for any number of looping schemes
  • 不涉及变量设置(迭代数组的每个元素)
  • 函数/箭头函数作用域变量到块
    在上面的例子中,val将是新创建函数的参数。因此,val在循环之前调用的任何变量将在循环结束后保持它们的值。
  • 主观上更易于维护,因为它可能更容易识别代码在做什么——它正在迭代一个可枚举;而 for 循环可用于任意数量的循环方案


Performance

表现

Performance is a tricky topic, which generally requires some experience when it comes to forethought or approach. In order to determine ahead of time (while developing) how much optimization may be required, a programmer must have a good idea of past experience with the problem case, as well as a good understanding of potential solutions.

性能是一个棘手的话题,通常需要一些经验来进行深谋远虑或方法。为了提前(在开发时)确定可能需要多少优化,程序员必须对问题案例的过去经验有很好的了解,并对潜在的解决方案有很好的理解。

Using jQuery in some cases may be too slow at times (an experienced developer may know that), whereas other times may be a non-issue, in which case the library's cross-browser compliance and ease of performing other functions (e.g., AJAX, event-handling) would be worth the development (and maintenance) time saved.

在某些情况下使用 jQuery 有时可能太慢(有经验的开发人员可能知道这一点),而其他时候可能不是问题,在这种情况下,库的跨浏览器合规性和执行其他功能的简易性(例如,AJAX、事件处理)将值得节省开发(和维护)时间。

Another example is, if performance and optimization was everything, there would be no other code than machine or assembly. Obviously that isn't the case as there are many different high level and low level languages, each with their own tradeoffs. These tradeoffs include, but are not limited to specialization, development ease and speed, maintenance ease and speed, optimized code, error free code, etc.

另一个例子是,如果性能和优化就是一切,那么除了机器或程序集之外就没有其他代码了。显然情况并非如此,因为有许多不同的高级和低级语言,每种语言都有自己的权衡。这些权衡包括但不限于专业化、开发简易性和速度、维护简易性和速度、优化代码、无错误代码等。

Approach

方法

If you don't have a good understanding if something will require optimized code, it's generally a good rule of thumb to write maintainable code first. From there, you can test and pinpoint what needs more attention when it's required.

如果您不能很好地理解某些东西是否需要优化代码,那么首先编写可维护的代码通常是一个很好的经验法则。从那里,您可以测试并确定需要时需要更多关注的内容。

That said, certain obvious optimizations should be part of general practice and not required any thought. For instance, consider the following loop:

也就是说,某些明显的优化应该是一般实践的一部分,不需要任何思考。例如,考虑以下循环:

for (var i=0; i < arr.length; ++i ){}

For each iteration of the loop, JavaScript is retrieving the arr.length, a key-lookup costing operations on each cycle. There is no reason why this shouldn't be:

对于循环的每次迭代,JavaScript 都会arr.length在每个循环中检索键查找成本计算操作。没有理由不应该是:

for (var i=0, n=arr.length; i < n; ++i){}

This does the same thing, but only retrieves arr.lengthonce, caching the variable and optimizing your code.

这做同样的事情,但只检索arr.length一次,缓存变量并优化你的代码。