views:

103

answers:

1

Hy

Is there any performance difference between:

(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?

+5  A: 

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
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
@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
@Jon Skeet: I agree. Was only for completeness.
Ani