Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the compiler concatenate LINQ where queries?

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

  1. Is one more efficient than the other?
  2. Is the compiler smart enough to optimize this?
like image 972
Steven Jeuris Avatar asked Sep 11 '11 23:09

Steven Jeuris


2 Answers

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.

like image 178
Eric Lippert Avatar answered Sep 20 '22 12:09

Eric Lippert


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.

like image 37
Raymond Chen Avatar answered Sep 19 '22 12:09

Raymond Chen