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

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

问题描述

在技术采访中的另一天,问题之一是你如何优化Javascript代码?

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

令我惊讶的是,他告诉我,虽然循环通常比循环更快。

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循环性能 - 为什么将迭代器减少到比递增更快的速度为止的时间

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.

在这两个来源中,这两个来源通过运行各种循环很好地记录了速度现象。不同的浏览器并以毫秒为单位比较结果:
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(var k=0; ++k; k< 20){ ... }

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

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性能:虽然vs For循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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