There are three reasons you might use And
rather than AndAlso
(and while VB.Net operators are not always directly comparable with C# operators, this does apply to &
vs &&
in C# too).
The first is when you are not comparing boolean values, but doing a bit-wise comparison.
13 And 92 ' 12
13 AndAlso 92 ' True
The second is when you want to ensure that both expressions are calculated because of a side effect. However, in such a case I'd recommend you calculate them first and then do the And
or AndAlso
after, to make for clearer code.
The third is to avoid branching. Consider that:
If x AndAlso y Then
' Do something
End If
Works much the same as:
If x Then
If y Then
' Do Something
End If
End If
Now, with the way that modern computers work, processors will have read some of the next instructions before knowing whether those are really the next instructions or not, because it has yet to work out whether it will follow an If
branch or not. There's some clever stuff guessing about whether a branch will be taken or not, but that clever stuff is still just guessing. If it guesses wrong then it has to back up and this slows things down.
Therefore if calculating the second argument to an AndAlso
takes less than a certain threshold, a And
could in fact be faster, because while there is conceptually more work done in with an And
than an AndAlso
in the case where the first argument was False
(allowing the AndAlso
to short-circuit) there's only one branch to predict rather than two, and the odds of correctly guessing which the branching is greater. (Search for "branch prediction" and "branch misprediction" here for more on that general issue).