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

  • Pergunta

  • 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
    segunda-feira, 17 de agosto de 2020 14:12

Todas as Respostas

  • 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

    segunda-feira, 17 de agosto de 2020 14:24
  • See the accepted answer in this post, could had written this up myself but it's already out there.

    https://stackoverflow.com/questions/23536541/performance-between-iterating-through-ienumerablet-and-listt


    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.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Sugerido como Resposta Naomi N segunda-feira, 17 de agosto de 2020 15:20
    segunda-feira, 17 de agosto de 2020 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.

    segunda-feira, 17 de agosto de 2020 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.

    terça-feira, 18 de agosto de 2020 10:09