niao
niao

Reputation: 5070

Linq, lambda - which statement is faster?

I was wondering which expression is faster and which one is preferred:

myList.Select(a => a.Property)
      .Where(a => !String.IsNullOrEmpty(a))

myList.Where(a => !String.IsNullOrEmpty(a.Property))
      .Select(a => a.Property)

and of course why?

Generally my question is: should I use Where followed by Select or Select followed by Where?

Upvotes: 0

Views: 723

Answers (4)

Amy B
Amy B

Reputation: 110111

No one can know, you must measure. Consider a list of 50 items, with 40 items meeting the filter criteria.

Project then filter, this approach minimizes the number of accesses to a.Property. 100 anonymous method invocations and 50 property accesses.

myList
   .Select(a => a.Property)
   .Where(a => !String.IsNullOrEmpty(a))

Filter then project, this approach minimizes the number of calls to anonymous methods. 90 anonymous method invocations and 90 property accesses.

myList
   .Where(a => !String.IsNullOrEmpty(a.Property))
   .Select(a => a.Property) 

Since we don't know the costs of your property's implementation vs the costs of an anonymous method invocation, there's no way to reason about the performance difference.

Upvotes: 1

Eamon Nerbonne
Eamon Nerbonne

Reputation: 48066

It doesn't much matter. In cases such as the above, where the remainder of the "query" only references the projected data, you may as well project first and then filter.

Note that it's not the case that filtering first is necessarily faster; by calling Select first you will be executing fewer property accessors - but the difference is likely to be minor either way.

If you're going to write more complex queries, I suggest writing reducing the scope of the data as quickly as you can, which in this case means writing the Select before the Where: that results in shorter code which is more readable in longer queries: after all, by focusing only on the relevant bits (here strings) the reader can ignore the more complex objects containing them in the rest of the query. This advantage is fairly pointless for such a small query, however.

Upvotes: 0

Carlos Muñoz
Carlos Muñoz

Reputation: 17804

It depends on the Linq provider.

For example in Linq2Sql both statements are the same since thwy will generate the same SQL against the database.

In Linq2Objects it may perform diferently.

Upvotes: 0

decyclone
decyclone

Reputation: 30830

I would prefer the second one, where you filter the data first (using Where) and then select (using Select) what data you want.

Depending on the data you are filtering performance may vary, but I feel the second one is more in flow.

Upvotes: 1

Related Questions