简体   繁体   English

for循环与for循环反向:性能

[英]for loop vs for loop in reverse: performance

According to What's the Fastest Way to Code a Loop in JavaScript? 根据用JavaScript编写循环的最快方法是什么? and Why is to decrement the iterator toward 0 faster than incrementing , a basic for loop is slower than a for - loop with simplified test condition, ie: 以及为什么要以比递增快的速度将迭代器递减到0 ,基本的for循环要比for-循环慢for且测试条件简化,即:

 console.log("+++++++"); var until = 100000000; function func1() { console.time("basic") var until2 = until; for (var i = 0; i < until2; i++) {} console.timeEnd("basic") } function func2() { console.time("reverse") var until2 = until; for (until2; until2--;) {} //while(until2--){} console.timeEnd("reverse") } func1(); func2(); 

As you might see the first function is, contrary to expectations, faster than the second. 您可能会看到,第一个功能与预期相反,比第二个要快。 Did something change since the release of this oracle article, or did I do something wrong? 自从此oracle文章发布以来,是否发生了某些变化?或者我做错了什么?

Yes, something has changed since the article was released. 是的,自文章发布以来,情况有所变化。 Firefox has gone from version 3 to version 38 for one thing. Firefox一开始就从版本3升到了版本38。 Mostly when a new version of a browser is released, the performance of several things has changed. 通常,当发布新版本的浏览器时,几件事的性能已经改变。

If you try that code in different versions of different browsers on different systems, you will see that you will get quite a difference in performance. 如果您在不同系统上的不同浏览器的不同版本中尝试该代码,则会发现性能会有所不同。 Different browsers are optimised for different Javascript code. 不同的浏览器针对不同的Javascript代码进行了优化。

As performance differs, and you can't rely on any measurements to be useful for very long, there are basically two principles that you can follow if you need to optimise Javascript: 由于性能不同,并且您不能长期依赖任何度量,因此,如果需要优化Javascript,基本上可以遵循两个原则:

  • Use the simplest and most common code for each task; 对每个任务使用最简单,最通用的代码; that is the code that browser vendors will try to optimise the most. 这是浏览器供应商将尝试最优化的代码。

  • Don't look for the best performance in a specific browser, look for the worst performance in any brower. 不要在特定浏览器中寻找最佳性能,而要在任何浏览器中寻找最差性能。 Test the code in different browsers, and pick a method that doesn't give remarkably bad performance in any of them. 在不同的浏览器中测试代码,并选择一种不会在任何一种浏览器中均带来明显不良性能的方法。

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

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