[Solved] Which loop more efficient/preferable – foreach or while loop [closed]


Well it doesn’t matter if you choose to use a foreach or while loop because a foreach loop is actually broken into a while loop after it has been compiled to IL.

Take a look at this foreach loop:

IEnumerable<int> enumerable = Enumerable.Range(1, 100);
 foreach (int e in enumerable)
 {

 }

After it has been compiled to IL it looks like this:

var enumerable = Enumerable.Range(1, 100);
IEnumerator<int> enumerator = enumerable.GetEnumerator();
try
{
    while (enumerator.MoveNext())
    {
        int element = enumerator.Current;
        //here goes your action instructions
    }
}
finally
{
    IDisposable disposable = enumerator as System.IDisposable;
    if (disposable != null) disposable.Dispose();
}

I would always prefer the more readable code which definitly is the foreach loop.
For further information read this great article: http://www.abhisheksur.com/2011/01/internals-of-loops-while-for-and.html

solved Which loop more efficient/preferable – foreach or while loop [closed]