Javascript 效率:'for' 与 'forEach' [英] Javascript efficiency: 'for' vs 'forEach'

查看:24
本文介绍了Javascript 效率:'for' 与 'forEach'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我目前正在 Udemy 上通过 Colt Steeles 的Web Dev Bootcamp"工作,他在教学中更喜欢 forEach 而不是 for.然而,作为课程作业的一部分,我在练习期间搜索了各种内容,我发现越来越多的建议使用 for 循环而不是 forEach.大多数人似乎都说 for 循环更有效.

I am currently working my way through Colt Steeles "Web Dev Bootcamp" on Udemy and he favours forEach over for in 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.

这是否自课程编写(大约 2015 年)以来发生了变化,或者它们各自的真​​正优点和缺点,谁会随着更多的经验而学习.

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.

任何建议将不胜感激.

推荐答案

for

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

for

for loops 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 (var i=0, n=arr.length; i < n; ++i ) {
   ...
}

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

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 [].forEach could be implemented in such a way that it's faster or comparable to a for.

  • 高效
  • 早期循环终止(荣誉 breakcontinue)
  • 条件控制(i 可以是任何东西,不受数组大小限制)
  • 变量作用域(var i 使 i 在循环结束后可用)
  • efficient
  • early loop termination (honors break and continue)
  • condition control (i<n can be anything and not bound to an array's size)
  • variable scoping (var i leaves i available after the loop ends)

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

.forEach are methods that primarily iterate over arrays (also over other enumerable, such as Map and Set objects). They are newer and provide code that is subjectively easier to read. Example:

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

优点:

  • 不涉及变量设置(遍历数组的每个元素)
  • 函数/箭头函数将变量作用域到块
    在上面的示例中,val 将是新创建函数的参数.因此,任何在循环之前称为 val 的变量在循环结束后都会保持它们的值.
  • 主观上更易于维护,因为它可能更容易识别代码在做什么——它正在迭代一个可枚举;而 for 循环可用于任意数量的循环方案
  • 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, val would be a parameter of the newly created function. Thus, any variables called val before 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
    • 性能是一个棘手的话题,在涉及到远见卓识或方法时,通常需要一些经验.为了提前(在开发时)确定可能需要进行多少优化,程序员必须对问题案例的过去经验有很好的了解,并对潜在的解决方案有很好的理解.

      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.

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

      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.

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

      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.

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

      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 ){}
      

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

      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:

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

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

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

      这篇关于Javascript 效率:'for' 与 'forEach'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆