Is order of the predicate important when using LINQ?

前端 未结 1 583
我在风中等你
我在风中等你 2021-02-15 14:33

I understand that executing operations in different orders will yield different performance such as the difference between the following slow query:

List

        
相关标签:
1条回答
  • 2021-02-15 15:00

    The answer is going to be different for different LINQ providers. In particular, the story is very different for LINQ to Objects and say LINQ to Entities.

    In LINQ to Objects, the Where operator accepts the filter as Func<TSource, bool>. Func<,> is a delegate, so for the purposes of this discussion, you can think of it as a function pointer. In LINQ to Objects, your query is equivalent to this:

    static void Main() {
        List<TestItem> results = items.Where(MyFilter).ToList(); 
    
    static boolean MyFilter(TestItem item) {
        return item.Item1 == 12 && 
            item.Item2 != null && 
            item.Item2.SubItem == 65 && 
            item.Item3.Equals(anotherThingy)
    }
    

    The main thing to notice is that MyFilter is an ordinary C# method and so ordinary C# rules apply, including the short-circuiting behavior of &&. Consequently, the conditions will be evaluated in the order you wrote them. LINQ to Objects can invoke MyFilter on different input elements, but it cannot change what MyFilter does.

    In LINQ to Entities and LINQ to SQL, the Where operator accepts the filter as Expression<Func<TSource, bool>>. Now, the filter is passed into the Where operator as a data structure that describes the expression. In that case, the LINQ provider will look at the data structure (the "expression tree") and it is up to the LINQ provider to decide how to interpret it.

    In LINQ to Entities and LINQ to SQL cases, the expression tree will be translated to SQL. And then it is up to the database server to decide how to execute the query. The server is definitely allowed to reorder the conditions, and it may do even more substantial optimizations. For example, if the SQL table contains an index on one of the columns referenced in the condition, the server can choose to use the index and avoid even looking at rows that don't match that particular condition part.

    0 讨论(0)
提交回复
热议问题