Consider the two following similar code samples.
One where
clause.
bool validFactory
= fields
.Where(
fields => field.FieldType == typeof( DependencyPropertyFactory<T> ) &&
field.IsStatic )
.Any();
Two where
clauses.
bool validFactory
= fields
.Where( field => field.FieldType == typeof( DependencyPropertyFactory<T> ) )
.Where( field => field.IsStatic )
.Any();
I prefer the second since I find it more readable and it causes less formatting issues, especially when using auto-formatting. It is also clearer when placing comments next to the separate conditions (or even above) to clarify the intent.
My intuition says the second code sample would be less efficient. I could of course write a simple test myself (and will if nobody knows the answer). For now I thought this is perfect food for SO. ;p
The compiler does not attempt to optimize successive "where" calls. The runtime library does. If you have a whole bunch of "where" and "select" calls beside each other, the runtime will attempt to reorganize them into a more efficient form.
In some unusual cases, of course the "optimization" turns out to make things worse. I seem to recall that Jon Skeet wrote an article about that recently, though I'm not sure where it is.
The compiler is not allowed to optimize this because it doesn't know what Where() does. For example you may have overloaded Where() with a version which logs its results. (The jitter could do optimization, but in practice it is unlikely to.)
The efficiency difference is unlikely to be significant. You can profile your application to see if it matters.
Update: Apparently the jitter does perform optimization here. See Eric Lippert's answer.
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