What's faster iterating throught a list<T> or Ienumerable<T> RRS feed

  • 问题

  • is it better to use foreach on a list<T> or an Ienumerable<T>, i have the collection as Ienumerable so to make it a list i'll actually have to convert it, i'll only loop through the collection once so what's faster looping through the Ienumerable as is once or converting it to a list and then looping through it once
    2020年8月17日 14:12


  • I think when you iterating through collection it automatically converts it to list so you don't have to convert it prior (at least that's how I remember it). You may try to measure, I think the performance will be the same.

    Looking for new opportunities

    For every expert, there is an equal and opposite expert. - Becker's Law

    My blog

    My TechNet articles

    2020年8月17日 14:24
  • See the accepted answer in this post, could had written this up myself but it's already out there.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    profile for Karen Payne on Stack Exchange

    • 已建议为答案 Naomi N 2020年8月17日 15:20
    2020年8月17日 14:47
  • Creating a List from IEnumerable using ToList() will need time (even if the collection is already a List), probably a kind of additional internal enumeration.

    I think that you should perform some evaluation tests with typical and large collections.

    2020年8月17日 17:19
  • List is an instantiation of the Ienumerable type so you cannot really compare them.

    The interface allows multiple styles "listing" objects that obey the the IEnumerable interface to be assigned to that variable.

    As long as your generic type is the same when you simply assign list object to the interface variable the looping algorithm for the list object is used not the looping algorithm of the interface.

    The interface would not have an algorithm, merely a pointer to the implicit list algorithm.

    2020年8月18日 10:09