daryal
daryal

Reputation: 14919

Performance Comparison of Two Linq Calls

Assume that there are two queries running on a memory list;

First query (employing extension methods):

var temp = listX.Where(q => q.SomeProperty == someValue);

Second query:

var temp = from o in listX
              where o.SomeProperty == someValue
              select o;

Is there a difference between two queries in terms of performance; and if there is, why?

Upvotes: 3

Views: 181

Answers (3)

Spontifixus
Spontifixus

Reputation: 6660

Short question, short answer:

There is no difference. Both are the same, just written in different syntax.

See also the MSDN documentation for Query Syntax and Method Syntax.

Upvotes: 3

petko_stankoski
petko_stankoski

Reputation: 10713

There aren't differences. It will produce the same result in the same time. It's basically the same code with different syntax.

Upvotes: 4

Jon
Jon

Reputation: 437336

No, there is no difference at all. The compiler internally transforms the second version to the first one.

The C# specification (§7.6.12) states:

The C# language does not specify the execution semantics of query expressions. Rather, query expressions are translated into invocations of methods that adhere to the query expression pattern (§7.16.3). Specifically, query expressions are translated into invocations of methods named Where, Select, SelectMany, Join, GroupJoin, OrderBy, OrderByDescending, ThenBy, ThenByDescending, GroupBy, and Cast.These methods are expected to have particular signatures and result types, as described in §7.16.3. These methods can be instance methods of the object being queried or extension methods that are external to the object, and they implement the actual execution of the query.

The translation from query expressions to method invocations is a syntactic mapping that occurs before any type binding or overload resolution has been performed. The translation is guaranteed to be syntactically correct, but it is not guaranteed to produce semantically correct C# code. Following translation of query expressions, the resulting method invocations are processed as regular method invocations, and this may in turn uncover errors, for example if the methods do not exist, if arguments have wrong types, or if the methods are generic and type inference fails.

Upvotes: 8

Related Questions