Contrary to what might seem, the Entity Framework's LINQ codes will attempt to generate an SQL expression or something equivalent that processes the data in the database. It will not execute exactly the code that is written there. This is called Domain Specific Language (DSL). This should occur with the Where()
used before to get what is in the database.
But it should not occur with ForEach()
that does not exist in the EF LINQ provider. So the difference between them is almost syntactic.
In order to know which delay you would have to do tests. The problem is that both are abstractions that have cost. foreach
needs to get an iterator that is an object outside the collection to track the progress of each item. This is not free. Since ForEach()
of List
is a simple for
without iterator, which is faster. On the other hand it needs to call a delegate on each iteration, which is not for free. If I give a test later, but it will take time because I'm extremely busy and the internet problematic.
In general, it is used for Parallel processing which is not possible with the command foreach
, it is a little more expensive, but if there are gains (not always there) you can finish before running in parallel. In this case it is just a processing in the application on top of the result brought by the database.
There are people who like him in any situation because it gets shorter and eventually more semantic about what he wants to do. But the performance is not good if it does not parallel well. And parallelization is not available in every implementation of ForEach()
. Contrary to what people imagine it is not a single method, it can have several flavors.
See more: