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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With