Should the order of LINQ query clauses affect Entity Framework performance?

后端 未结 4 2085
灰色年华
灰色年华 2020-12-06 04:33

I\'m using Entity Framework (code first) and finding the order I specify clauses in my LINQ queries is having a huge performance impact, so for example:

usin         


        
4条回答
  •  感动是毒
    2020-12-06 05:06

    Note: I ran into this question long after others have already provided generally correct answers. I decided to post this as a separate answer only because I think the workaround can be helpful, and because you might appreciate having a better insight on the reason EF behaves this way.

    Short answer: The best workaround for this issue is to set this flag on your DbContext instance:

    context.Configuration.UseDatabaseNullSemantics = true;
    

    When you do this all the extra null checks will go away and your queries should perform faster if the were affected by this issue.

    Long answer: others in this thread are right that in EF6 we have introduced the extra null checking terms by default to compensate for differences between the semantics of null comparisons in the database (three-valued logic) and standard in-memory null comparisons. The goal of this is to satisfy the following very popular request:

    Incorrect handling of null variables in 'where' clause

    Paul White is also right that the in the following expression the 'AND NOT' part is less common in for compensating for three-valued logic:

    ((x = y) AND NOT (x IS NULL OR y IS NULL)) OR (x IS NULL AND y IS NULL)
    

    That extra condition is necessary in the general case to prevent the result from the whole expression to be NULL, e.g. assume that x = 1 and y = NULL. Then

    (x = y) --> NULL 
    (x IS NULL AND y IS NULL) --> false
    NULL OR false --> NULL
    

    The distinction between NULL and false is important in case the comparison expression is negated at a later point in the composition of the query expression, e.g.:

    NOT (false) --> true 
    NOT (NULL) --> NULL
    

    It is also true that we could potentially add the smarts to EF to figure out when this extra term is unnecessary (e.g. if we know that the expression isn't negated in the predicate of the query) and to optimize it out of the query.

    By the way, we are tracking this issue in the following EF bug at codeplex:

    [Performance] Reduce the expression tree for complex queries in case of C# null comparison semantics

提交回复
热议问题