views:

156

answers:

3

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?

+14  A: 

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.

Andrew Hare
+3  A: 

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.

Ian Ringrose
+1  A: 

They will not compile to the same code. In the second version X is evaluated many times and myList is enumerated. Worst case scenario is evaluating X changes something, and you have unpredictable functionality.

Yuriy Faktorovich