Is it costly to do array.length or list.count in a loop

前端 未结 6 655
梦谈多话
梦谈多话 2020-12-10 01:18

I know that in JavaScript, creating a for loop like this: for(int i = 0; i < arr.length; i++) is costly as it computes the array length each time. Is this be

6条回答
  •  暖寄归人
    2020-12-10 02:07

    In almost any language, the answer will be "it depends".

    Mostly, it depends on whether the compiler is clever enough to be able to tell whether the length of the list or array might change whilst you're in the loop.

    That's unlikely to be defined by the language specification, though.

    So, it's probably safe to assume that the compile may not be able to figure that out. If you really truly believe that the length of the object won't change, feel free to calculate the length first and use that in your loop control constructs.

    But beware of other threads...

提交回复
热议问题