Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which LINQ query is more effective?

Tags:

c#

linq

I have a huge IEnumerable(suppose the name is myItems), which way is more effective?

Solution 1: Filter it first then ForEach.

Array.ForEach(myItems.Where(FILTER-IT-HERE).ToArray(),MY-ACTION);

Solution 2: Do RETURN in MY-ACTION if the item is not up to the mustard.

Array.ForEach(myItems.ToArray(),MY-ACTION-WITH-FILTER);

Is one of them always better than another? Or any other good suggestions? Thanks in advance.

like image 900
Cheng Chen Avatar asked Feb 03 '26 09:02

Cheng Chen


2 Answers

Did you do any measurements? Since WE can't measure the run time of My-Action then only you can. Measure and decide.

like image 71
Jared Peless Avatar answered Feb 05 '26 00:02

Jared Peless


Sometimes one has to create benchmark's because similar looking activities could produce radically different and unexpected results.

You do not say what your data source is so I'm going to assume it may be data on an SQL server in which case filtering at the server side will likely always be the best approach because you have minimized the amount of data transfer. Memory access is always faster than data transfer from disk to memory so whenever you can transfer fewer records, you are likely to have better performance.

like image 45
gerryLowry Avatar answered Feb 04 '26 23:02

gerryLowry