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

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

问题描述



目前我正在通过Colt Steeles的方式Web Dev Bootcamp 在Udemy和他在他的教导中赞成 forEach 超过 。然而,我已经在练习期间搜索了各种各样的东西,作为课程工作的一部分,我发现越来越多的建议使用作为 -loop而不是的forEach 。大多数人似乎认为for循环更有效率。



这是自课程编写以来(2015年左右)发生了什么变化,还是它们真正的优点和缺点每一个,哪一个将学习更多的经验。

任何意见将不胜感激。

解决方案 for

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

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b ...
}

这并不是说 / em> - 回环将永远更高效,只是JS引擎和浏览器已经优化它们。多年以来,对于哪个循环结构更高效(同时减少,反向等等)已经有了妥协 - 不同的浏览器和JS引擎都有自己的实现,它们提供了不同的方法来产生相同的结果。当浏览器进一步优化以满足性能需求时,理论上 [] .forEach 可以以这样的方式实现,即它的速度更快或者与 code>。



好处:




  • 高效

  • 早期循环终止(honors break continue

  • 条件控制( i 可以是任何东西而不是绑定到数组的大小)
  • 变量作用域( var i 在循环结束后可以使用 i


    forEach



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

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



    好处:




    • 不涉及变量设置(对数组的每个元素进行迭代)
    • 函数/箭头函数将变量作用于块
      在上面的示例中, val 将是新创建函数的参数。因此,任何在循环之前调用 val 的变量在它结束之后都会保存它们的值。
    • 主观上更易于维护,因为它可能更容易以确定代码在做什么 - 它遍历一个枚举;而for循环可以用于任何数量的循环方案
      $ b $ hr
      $ b

      性能



      表现是一个棘手的话题,当涉及到预谋或方法时,通常需要一些经验。为了提前确定(在开发过程中)可能需要多少优化,程序员必须对过去的问题情况有一个好的想法,以及对潜在的解决方案有一个很好的理解。

      在某些情况下使用jQuery的速度有时可能太慢(有经验的开发人员可能知道),而其他时间可能不是问题,在这种情况下,图书馆的跨浏览器合规性和易用性执行其他功能(例如,AJAX,事件处理)将是值得开发(和维护)的时间节省。另一个例子是,如果性能和优化是一切,除了机器或装配体之外,不会有其他的代码。很显然,情况并非如此,因为有许多不同的高级和低级语言,每种都有自己的折衷。这些权衡包括但不限于专业化,开发的方便和速度,维护的方便和速度,优化的代码,无错误的代码等。

      方法



      如果您不清楚是否需要优化代码,那么首先编写可维护的代码通常是一个很好的经验法则。从那里,你可以测试和确定什么时候需要更多的注意力。

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

      $ $ p $ code> for(var i = 0; i< arr.length; i ++){}

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

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

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

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

      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.

      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.

      Any advice would be greatly appreciated.

      解决方案

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

      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.

      Benefits:

      • 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

      .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)=>{
         ...
      });
      

      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

      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.

      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:

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

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

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

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