3

Possible Duplicate:
For vs Foreach loop in C#

Is one better than another?

Seems I've heard that a for loop has less overhead than a foreach, but I've yet to see the proof of this.

Community
  • 1
  • 1
jp2code
  • 24,618
  • 35
  • 140
  • 254
  • You have already answer: http://stackoverflow.com/questions/365615/in-net-which-loop-runs-faster-for-or-foreach – Senad Meškin Jul 13 '11 at 18:23
  • 1
    A for loop iterates over a single variable. A foreach loop requires an iterator object to be created, calls (possibly virtual) methods on the iterator, and requires disposal of the iterator. This may not be proof positive for you (hence why it's not an answer), but knowing this you may not *need* proof. – Erik Forbes Jul 13 '11 at 18:24
  • FYI: The duplicates did not pull up whenever I did my search - not on the first page, anyway. – jp2code Jul 13 '11 at 18:35

3 Answers3

2

Use foreach if you don't need the index (which is most of the time in most applications) otherwise use for.

Davy8
  • 29,246
  • 22
  • 107
  • 172
  • 1
    I would disagree, use `foreach` when you need basic transaction support. `foreach` will throw an exception if the collection is modified during enumeration--`for` will not – STW Jul 13 '11 at 18:39
2

The compiler of today has gotten a lot better than the compiler of .net 1.

While for is more optimized, foreach over an array is actually translated in the IL to a for. Foreach over a generic collection is optimized in that it returns a generic ienumerator and linq has some neato optimizations around that as well.

So the short answer is yes, but the real world answer is no.

Double Down
  • 858
  • 5
  • 13
2

One being "better" than the other depends on your application. Are you just reading a data structure? Are you writing to a data structure? Are you not even using any sort of data structure and just doing some math?

They each have their own uses. The for each loop is usually used for reading things from a data structure (array, linked list etc). For example.

foreach(myClass i in myList)
{
    int x = i.getX();
    console.writeline(x);
}

Where the for loop can be used to do the above, among other things such as update a data structure entry.

for (int i = 0; i < myList.count(); i++)
{
   myList[i].x += i * 80;
}
Ian Nelson
  • 51,299
  • 20
  • 72
  • 100
MGZero
  • 5,230
  • 4
  • 26
  • 42