javascript - for loop efficiency problem
黄舟
黄舟 2017-05-19 10:10:19
0
3
590

for (var i = 0, len = source.length; i < len; i )

Is

better than

for (var i = 0; i < source.length; i )

Is it efficient?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
PHPzhong

The first way of writing avoids calculating length every time and is more efficient than the second way of writing. (The number of loops is not many. In fact, there is not much difference between the two, but it is recommended to use the first way of writing)

刘奇

The second typeevery time it loops will get the length of the source,

The first method only obtains the value of the source length once and caches it in a variable. In the future, the value is obtained from the variable every time,

The first one is more efficient.

洪涛

Practice is the only criterion for testing understanding

var a = new Array(100).fill(0);

var a = new Array(1000).fill(0);

var a = new Array(10000).fill(0);

You can see from the results that the first way of writing has slightly better performance, but the first way will consume extra memory. Although front-end memory is free, for me personally, there is no difference between the two methods

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template