Enumerator or foreach - which one is better

I have a List<int> that say, has 10000 items in it. It is faster to get the enumerator object or do a foreach on it

Thanks

Ralph



Answer this question

Enumerator or foreach - which one is better

  • Robert Horvick MSFT

    That may well be slower than:

    for (int i=0; i < list.Count; i++)
    {
    ....
    }


    as the JIT is able to eliminate some bounds checking.

    However, I would use a foreach for the sake of readability (assuming the index isn't required separately). The performance hit - if any - is likely to be completely insignificant.

    Jon



  • Chris Rust

    Item 11 in Effective C# by Bill Wagner specifies "Prefer foreach loops".

    It goes on at some length to justify that suggestion, but it is too long for me to reproduce here. Some of them are noted here:

    http://www.brianpautsch.com/ShowItem16.aspx


  • Miles Thompson

    I Guest that the fast way is to use a normal for to iterate the List

    List<int> list = new List<int>();

    // Here we add the items to the list

    int length = list.Count;

    for (int i = 0; i < length; i++)

    {

    //Do you code for the list here.

    }



  • Enumerator or foreach - which one is better