Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ vs regular enumeration

When you have some enumeration methods in some of your types (i.e. a custom collection), is it better to use LINQ syntax or just old school enumeration (for/foreach)?

Using .NET 3.5 is a given.

I am asking this for maximum performance and readability. The application is also designed to be parallel.

Which one would you favor?

like image 509
Joan Venge Avatar asked Jun 10 '26 20:06

Joan Venge


2 Answers

Linq queries can be parallelised easily using PLinq (built into .net 4)

I personally find Linq easier to read, but it depends on you as a developer.

foreach (var item in collection)
{
    if (item.Value == SomeOtherValue)
        performSomeProcessing();
}

vs

foreach(var item in collection.Where(a => a.Value == SomeOtherValue))
{
    performSomeProcessing();
}

I think (although i've not personally benchmarked this) that the compiler optimises out the small function calls, so performance should not be noticably different.

like image 167
Matthew Steeples Avatar answered Jun 13 '26 12:06

Matthew Steeples


If you absolutely must wring every last drop of performance out, then a for/foreach loop is tough to beat for efficiency. However, if you're going for parallelism and readability, the Enumerable<T> extension methods and LINQ win hands down in my book.

like image 29
John Feminella Avatar answered Jun 13 '26 12:06

John Feminella



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!