C#: for verses foreach [duplicate]
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 proo开发者_开发知识库f of this.
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;
}
Use foreach
if you don't need the index (which is most of the time in most applications) otherwise use for
.
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.
精彩评论