我认为您可能会获得性能提升的一种可能情况是可枚举类型的大小和循环条件是否为常数;例如:
const int ArraySize = 10;
int[] values = new int[ArraySize];
//...
for (int i = 0; i
In this case, depending on the complexity of the loop body, the compiler might be able to replace the loop with inline calls. I have no idea if the .NET compiler does this, and it's of limited utility if the size of the enumerable type is dynamic.
One situation where foreach
might perform better is with data structures like a linked list where random access means traversing the list; the enumerator used by foreach
will probably iterate one item at a time, making each access O(1) and the full loop O(n), but calling the indexer means starting at the head and finding the item at the right index; O(N) each loop for O(n^2).
Personally I don't usually worry about it and use foreach
any time I need all items and don't care about the index of the item. If I'm not working with all of the items or I really need to know the index, I use for
. 唯一一次我认为这是一个大问题是链表之类的结构。