Which is better for performance? And vs AndAlso
When writing an If statement, I've always used And
when needed like:
If 1=1 And 2=2 Then
The only time I ever used AndAlso
is if the second开发者_JAVA百科 condition will error if the first isnt true like:
If Not IsDbNull(Value) AndAlso Value=2 Then
However, recently I've heard that AndAlso
is better for performance than And
as the second condition is only read when the first is true.
In this case, should I always just use AndAlso
?
Yes, AndAlso
can be faster than And
, because it doesn't evaluate subsequent conditions if an earlier condition proves false.
And
is a throwback to earlier versions of Visual Basic.
Most (I hesitate to say all) modern languages use boolean operators that short-circuit conditions that don't strictly need to be evaluated.
e.g. &&
the and operator for C style languages all perform as AndAlso
.
Be careful if you've lots of code that use And
and Or
, a global search and replace can change existing behaviour, if the second condition involves a function call that has side effects.
I would prefer using AndAlso
and OrElse
unless you specifically require the functionality provided by And
& Or
Coming from a C and C++ background into VB (V5 initially) it was always really annoying that VB's and
and or
didn't short circuit. So the case where the second expression was dependent on the first was always harder to write.
I wouldn't expect to see much of a performance increase most of the time, unless the second expression has significant overhead, short circuiting operators will avoid executing it and thus speeding things up.
But if that second expression is a significant overhead then I would be concerned about side effects which will only be performed sometimes—this will make future maintenance harder and could make correctness harder to maintain.
When the conditions are also functions:
If functionA() And functionB() Then
...
public shared functionA() As Boolean
IF A is false THEN log -> return true or false
...
public shared functionB() As Boolean
IF B is false THEN log -> return true or false
Using AndAlso
here could be the wrong way to go, because then it will only log B when both A and B are false.
精彩评论