Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing if(x) Foreach() with Foreach.Where(x)

Probably a stupid question but I have a lot of:

if(X)
{
  foreach(var Y in myList.Where(z => z == 1)
  {
  }
} 

constructs in some code
Is replacing it with

foreach(var Y in myList.Where(z => X && z == 1) { }

insane?

It is probably less readable, but will the compiler optimize it to make it pretty much the same code?

like image 492
Andrew White Avatar asked Sep 08 '10 15:09

Andrew White


2 Answers

No, your first version is better and faster. The second version will evaluate X for each element in the sequence whenever X is true.

You should stick with the first version.

like image 192
Andrew Hare Avatar answered Oct 06 '22 00:10

Andrew Hare


The 2nd option will be a lot slower when x is false, as you are making linq check all items in the list when you know the check will always fail.

The compiler optimizer will not be able to undo your damage. That level of optimization is only normally possible in functional languages as it is too hard for a compiler to track possible side effects.

Linq does not have optimizations built into it that is anywhere close to what you expect from a SQL query rewriter in a database.

like image 30
Ian Ringrose Avatar answered Oct 05 '22 23:10

Ian Ringrose