search

Home  >  Q&A  >  body text

javascript - for loop efficiency problem

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

Is

better than

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

Is it efficient?

黄舟黄舟2747 days ago593

reply all(3)I'll reply

  • PHPz

    PHPz2017-05-19 10:12:19

    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)

    reply
    0
  • 怪我咯

    怪我咯2017-05-19 10:12:19

    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.

    reply
    0
  • PHP中文网

    PHP中文网2017-05-19 10:12:19

    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

    reply
    0
  • Cancelreply