list.foreach vs foreach

Asked

Viewed 1,801 times

7

I have a list of several string, there’s a difference between going through the list values:

In this way:

ListaString.ForEach(delegate(string str)
{
    Console.WriteLine(str);
});

Or this:

foreach(string str in ListaString)
{
    Console.WriteLine(str);    
}

Is one more performatic than the other? Is there any significant gain?

When recommended to use list.foreach? and foreach? in the case of List<T>.

Note: I know that the Foreach can be used to browse arrays and other things.
But I want to know specifically these two ways put up in situations that involve List<T>.

  • 1

    Because it is an extension method (System.Linq) I believe that internally it should call the common foreach or something similar, so the performance should be very similar. As for the use, I believe it will go well. If it’s something simple, a simple call or a concatenation, I think the list.Foreach is more beautiful and simple to read.

2 answers

8


There’s a difference, of course. The first can be slower (there are controversies with my identical test) and it’s more confusing. It is so confusing that in the newer implementations of the class (such as the Winrt API, for example) it was even withdrawn as it brought no benefits and was abused.

  • the semantics is different
  • the way the enclosed variables are treated is different
  • is weird to read
  • it does not allow certain constructions, such as the continue and break
  • it is difficult to debug.

The first is considered more functional style, but there are those who disagree.

In general people do not understand the peculiarities of executing the loop within the method instead of the code being written there. Better to do what you understand best. If it will not bring you advantages and increases the chances of doing something wrong unintentionally, do not use.

And I’m talking about using with lambda and not with delegate that makes the code even bigger.

The Eric Lippert wrote about this.

Note that this is different from ForEachParallel that has advantages by doing parallelism, where it can be achieved and brings clear advantages in certain scenarios.

  • +1 for mentioning the ForEachParallel, a curious point about the foreach, is that when I try to call the SaveChanges() from the EF within the foreach, it triggers an exception stating that it cannot open a transaction, as it already exists in another thread, this behavior does not occur if the same code is rewritten using a conventional is never understood why.

  • @Tobymosque I don’t know why either, but it has to do with these semantic differences.

4

Next, in terms of performance there is no significant difference, you can even see this in the following fiddle:

https://dotnetfiddle.net

using System;
using System.Diagnostics;
using System.Linq;
                    
public class Program
{   
    public static void Main()
    {       
        var lista = Enumerable.Range(0, 50000).Select(indice => Guid.NewGuid()).ToList();
        
        var relogio = new Stopwatch();
        relogio.Start();
        
        for (var indice = 0; indice < lista.Count; indice++)
        {
            //var reverse = Enumerable.Reverse(lista[indice].ToByteArray());
        }
        Console.WriteLine(relogio.Elapsed);
        
        relogio.Restart();      
        foreach (var item in lista)
        {
            //var reverse = Enumerable.Reverse(item.ToByteArray());
        }
        Console.WriteLine(relogio.Elapsed);
        
        relogio.Restart();      
        lista.ForEach((item) => {
            //var reverse = Enumerable.Reverse(item.ToByteArray());
        });
        Console.WriteLine(relogio.Elapsed);
    }
}

Another point I would like to mention is that Linq does not implement an extensive Foreach method for the Ienumerable Interface, we only have the native List method.

I would also like to point out the justification given by Eric Lippert at Link:

foos.ForEach((Foo foo)=>{ statement involving foo; }); is difficult to read and debug, besides can introduce other problems.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.