开发者

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 =开发者_如何学Python> a.Property)

and of course why?

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


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜