views:

429

answers:

6

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?

+12  A: 

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.

Konrad Rudolph
What is inlinking, inlining?
maxfridbe
It's a typo. ;-) Thanks.
Konrad Rudolph
as for JavaScript, you use the "(var i=0,mi=arr.length; i<mi; ++i)" junk for IE, where it's plenty slower to check array length every iteration.Think all the other browsers handle it fine.
Sciolist
+2  A: 

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...

Alnitak
Well, for languages such as C#, the answer is definitely not “it depends” since the behaviour is quite well documented.
Konrad Rudolph
A: 

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

A: 

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

warren
+3  A: 
  1. All .Net arrays have a field containing the length of the array, so the length is not computed at usage but at creation time.

  2. 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).

Pop Catalin
A: 

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

NotDan
Not for arrays, no. For arrays, `Count` simply calls the `Length` property.
Konrad Rudolph