EDIT: This question can be marked as a duplicate of this question.
Is there any differences (performance or otherwise) between using a foreach loop or the ForEach
LINQ
method?
For context, this is part of one of my methods:
foreach (var property in typeof(Person).GetProperties())
{
Validate(property.Name);
}
I can alternatively use this code to perform the same task:
typeof(Person)
.GetProperties()
.ToList()
.ForEach(property => Validate(property.Name));
When would be using the loop structure be better than using method chaining?
Here's another example where I've used the ForEach
method, but could just have easily used a foreach loop and a variable:
// LINQ
PrivateData.Database.Users
.Cast<User>()
.Where(user => user.LoginType == LoginType.WindowsUser)
.Select(user => new { Name = user.Name, Login = user.Login })
.ToList()
.ForEach(result => WriteObject(result));
// Loop
var users = PrivateData.Database.Users
.Cast<User>()
.Where(user => user.LoginType == LoginType.WindowsUser)
.Select(user => new { Name = user.Name, Login = user.Login });
foreach(var user in users)
{
WriteObject(user);
}
forEach LoopIt is faster in performance. It is slower than the traditional loop in performance. The break statement can be used to come out from the loop.
For Loops executes a block of code until an expression returns false while ForEach loop executed a block of code through the items in object collections. For loop can execute with object collections or without any object collections while ForEach loop can execute with object collections only.
The map() method returns an entirely new array with transformed elements and the same amount of data. In the case of forEach() , even if it returns undefined , it will mutate the original array with the callback . Therefore, we see clearly that map() relies on immutability and forEach() is a mutator method.
each differs for the arguments passed to the callback. If you use _. forEach , the first argument passed to the callback is the value, not the key.
I would defer you to Eric Lipperts blog "foreach" vs "ForEach". As the previous principal developer on the C# compiler team, I think his opinion is spot on.
Excerpt: (referring to .ForEach()
)
The first reason is that doing so violates the functional programming principles that all the other sequence operators are based upon. Clearly the sole purpose of a call to this method is to cause side effects. The purpose of an expression is to compute a value, not to cause a side effect. The purpose of a statement is to cause a side effect. The call site of this thing would look an awful lot like an expression (though, admittedly, since the method is void-returning, the expression could only be used in a “statement expression” context.) It does not sit well with me to make the one and only sequence operator that is only useful for its side effects.
The loop is better style because it is a tool made exactly for what you want to do. It integrates nicer with the language. For example, you can break from a loop. Tools understand loops, they do not understand ForEach
.
The loop is easier to understand for humans as well. ForEach
is very uncommon.
The loop also is faster because there are less indirect calls, less delegate allocations and the optimizer can see more of what you are doing in one place. It also saves the ToList
call. You could save that call by writing a custom extension method on IEnumerable<T>
as well.
I think the loop is superior in all cases that I can think of. Maybe there's some corner case where the ForEach
method would be better style or more convenient for some reason.
PLINQ also has a ForAll
which is required for efficiency reasons because it can be parallelized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With