[ACCEPTED]-Is it costly to do array.length or list.count in a loop-language-features

Accepted answer
Score: 37

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

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

Score: 10
  1. All .Net arrays have a field containing 7 the length of the array, so the length is 6 not computed at usage but at creation time.

  2. The 5 .Net virtual machine is very good at eliminating 4 bounds checks whenever possible, this is 3 one of those cases, where the bounds check 2 is moved outside the loop (in most situations, and 1 if not it's just 2 instructions overhead).

Edit:

Array Bounds Check Elimination

Score: 4

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

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

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

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

But beware 1 of other threads...

Score: 1

I believe if you use the Linq Count() extension 2 method, then it may calculate every time 1 it's called.

Score: 0

If it's anything like Java, it should be 2 an O(1) operation.

I found the following 1 link helpful: http://www.devguru.com/Technologies/Ecmascript/Quickref/array.html

Score: 0

It will also depend on whether that getter 2 is doing a calculation, or accessing a known 1 value.

More Related questions