I understand that && short-circuits the evaluation so it doesn’t have to evaluate the RHS if it doesn’t have to but what about EF? Is there any differences between & and && (same for | and ||)? performance-wise!
but what about EF? Is there any differences between & and && (same for | and ||)? performance-wise!
Yes, there is.
First, sometimes EF Core uses client evaluation, so it can't be short-circuited.
Second, even when using server evaluation, EF Core translates them differently. For instance, here is the translation for SqlServer:
LINQ SQL
============== ============
expr1 && expr2 expr1 AND expr2
expr1 & expr2 (expr1 & expr2) = 1
Whether this affects the performance depends of the database query optimizer, but the first looks generally better. And some database providers which has no native support for bool
type might generate quite inefficient translation or even fail to translate the &
/ |
predicates.
Shortly, preferably always use logical &&
and ||
operators in LINQ queries.
According to Microsoft Documentation:
1.The & Operator is supported in two forms: a unary address-of operator or a binary logical operator.
Unary address-of operator:
The unary &
operator returns the address of its operand. For more information, see How to: obtain the address of a variable . The address-of operator &
requires unsafe context.
Integer logical bitwise AND operator:
For integer types, the &
operator computes the logical bitwise AND
of its operands:
uint a = 0b_1111_1000;
uint b = 0b_1001_1111;
uint c = a & b;
Console.WriteLine(Convert.ToString(c, toBase: 2));
// Output:
// 10011000
2.The && Operator is the conditional logical AND operator, also known as the "short-circuiting" logical AND operator, computes the logical AND of its bool operands. The result of x && y
is true if both x
and y
evaluate to true
. Otherwise, the result is false
. If the first operand evaluates to false
, the second operand is not evaluated and the result of operation is false
.The following example demonstrates that behavior:
bool SecondOperand()
{
Console.WriteLine("Second operand is evaluated.");
return true;
}
bool a = false && SecondOperand(); // <-- second operand is not evaluated here
Console.WriteLine(a);
// Output:
// False
bool b = true && SecondOperand(); // <-- second operand is evaluated here
Console.WriteLine(b);
// Output:
// Second operand is evaluated.
// True
Now in case of EF/EF Core behavior @Ivan Stoev explained it greatly: Here