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

前端 未结 6 660
梦谈多话
梦谈多话 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 01:53

    It is not costly in C#. For one thing, there is no “calculation“: querying the length is basically an elementary operation thanks to inlining. And secondly, because (according to its developers), the compiler recognizes this pattern of access and will in fact optimize any (redundant) boundary checks for access on array elements.

    And by the way, I believe that something similar is true for modern JavaScript virtual machines, and if it isn't already, it will be very soon since this is a trivial optimization.

提交回复
热议问题