44

Is there any performance difference between the following two statements?

from item in collection 
where item.id == 3
select item

and

collection.Where(item => item.id ==3)

In general, is there any performance difference between the LINQ syntax and the method chain?

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
Radu D
  • 3,505
  • 9
  • 42
  • 69
  • 1
    More correctly it is "comprehension expression", and "fluent interface" (in the former case because the C# query syntax is not tied to LINQ, and in the latter because that's what method chaining is generally called). – Richard Sep 23 '10 at 09:37

1 Answers1

57

No, because they are compiled into exactly the same code.

Basically query expressions are "pre-processed" by the compiler into "C# 3 without query expressions" and then the rules of overloading, lambda expression translation etc are applied as normal. It's a really elegant system which means that the rules for query expressions are limited to just one small bit of the spec.

Of course, there are various things you can write in "chained method" syntax which can't be written in query expression syntax, either due to using other overloads or the methods simply not being supported (e.g. Count()) - but unless you're using those, the compiled code will be exactly the same. Pick the most readable alternative for any particular scenario.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • For completeness, given that the question relates to performance, it may be prudent to mention that there may be minor differences in *compilation* times between the two alternatives; the second alternative will probably be faster. – Ani Sep 23 '10 at 08:46
  • 9
    @Ani: In my experience, questions about performance are very *very* rarely about compilation speed. I'd expect the OP to *explicitly* specify that if that's what he meant. I think it's reasonable to assume that "performance" means "performance at execution time" unless otherwise stated. – Jon Skeet Sep 23 '10 at 08:50
  • I agree. Was only for completeness. – Ani Sep 23 '10 at 09:01
  • @JonSkeet - Just out of curiosity, do you have a preference between which to use? – Travis J May 12 '13 at 19:15
  • 5
    @TravisJ: Whichever is simplest for the particular situation. I like query expressions for joins and groupings - anything which would introduce a transparent identifier - but for more straightforward queries I like straight method invocations. – Jon Skeet May 12 '13 at 21:33
  • Does that mean the query syntax will take longer time to compile? – Just a learner Feb 05 '17 at 18:19
  • @OgrishMan: I doubt that you'd ever notice it - I haven't written any tests for that, but I'd be astonished if it were ever significant. – Jon Skeet Feb 05 '17 at 20:30