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 behavior costly in c# for lists and arrays as well. Or at compile-time is it optimized? Also what about other languages such as Java, how is this handled?
views:
429answers:
6It 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.
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...
If it's anything like Java, it should be an O(1) operation.
I found the following link helpful: http://www.devguru.com/Technologies/Ecmascript/Quickref/array.html
It will also depend on whether that getter is doing a calculation, or accessing a known value.
All .Net arrays have a field containing the length of the array, so the length is not computed at usage but at creation time.
The .Net virtual machine is very good at eliminating bounds checks whenever possible, this is one of those cases, where the bounds check is moved outside the loop (in most situations, and if not it's just 2 instructions overhead).
I believe if you use the Linq Count() extension method, then it may calculate every time it's called.