パフォーマンスが向上する可能性のある状況の1つは、列挙可能な型のサイズとループ条件が定数である場合だと思います。例えば:
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
。それが大きな懸念事項であることがわかったのは、リンクリストのような構造だけです。