Javascript 性能:While 与 For 循环 [英] Javascript Performance: While vs For Loops

查看:47
本文介绍了Javascript 性能:While 与 For 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前几天在一次技术面试中,被问到的一个问题是你如何优化 Javascript 代码"?

The other day during a tech interview, one of the question asked was "how can you optimize Javascript code"?

令我惊讶的是,他告诉我 while 循环通常比 for 循环快.

To my own surprise, he told me that while loops were usually faster than for loops.

这是真的吗?如果是,为什么会这样?

Is that even true? And if yes, why is that?

推荐答案

您应该反驳说,负 while 循环会更快!请参阅:JavaScript 循环性能 -为什么将迭代器递减到 0 比递增更快.

You should have countered that a negative while loop would be even faster! See: JavaScript loop performance - Why is to decrement the iterator toward 0 faster than incrementing.

whilefor 中,这两个来源通过在不同浏览器中运行各种循环并以毫秒为单位比较结果,很好地记录了速度现象:https://blogs.oracle.com/greimer/entry/best_way_to_code_a 和:http://www.stoimen.com/blog/2012/01/24/javascript-performance-for-vs-while/.

In while versus for, these two sources document the speed phenomenon pretty well by running various loops in different browsers and comparing the results in milliseconds: https://blogs.oracle.com/greimer/entry/best_way_to_code_a and: http://www.stoimen.com/blog/2012/01/24/javascript-performance-for-vs-while/.

从概念上讲,for 循环基本上是一个打包的 while 循环,专门针对递增或递减(根据某种顺序或某种长度在逻辑上进行).例如,

Conceptually, a for loop is basically a packaged while loop that is specifically geared towards incrementing or decrementing (progressing over the logic according to some order or some length). For example,

for (let k = 0; ++k; k < 20) {…}

可以通过将其设置为负的 while 循环来加速:

can be sped up by making it a negative while loop:

var k = 20;
while (--k) {…}

从上面链接中的测量结果可以看出,对于非常大的数字,节省的时间确实加起来.

and as you can see from the measurements in the links above, the time saved really does add up for very large numbers.

这篇关于Javascript 性能:While 与 For 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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