问题描述
在编写If语句时,我总是在需要时使用和
,如:
When writing an If statement, I've always used And
when needed like:
If 1=1 And 2=2 Then
我唯一使用过的时间 AndAlso
如果第二个条件会出错,如果第一个条件不是这样的话:
The only time I ever used AndAlso
is if the second condition will error if the first isnt true like:
If Not IsDbNull(Value) AndAlso Value=2 Then
然而,最近我听说过 AndAlso
的性能优于和
,因为只有当第一个条件为真时才会读取第二个条件。
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.
在这种情况下,我应该只使用 AndAlso
?
In this case, should I always just use AndAlso
?
推荐答案
是的, AndAlso
可以快于和
,因为它不会如果先前的条件证明是错误的,则评估后续条件。
Yes, AndAlso
can be faster than And
, because it doesn't evaluate subsequent conditions if an earlier condition proves false.
和
是对早期版本的Visual Basic的回归。 br>
大多数(我毫不犹豫地说)所有现代语言都使用布尔运算符那些不严格需要评估的短路情况。
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.
例如。 &&
C风格语言的和运算符都表现为 AndAlso
。
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.
我更喜欢使用 AndAlso
和 OrElse
除非您特别要求和
&提供的功能。 或
I would prefer using AndAlso
and OrElse
unless you specifically require the functionality provided by And
& Or
这篇关于哪个性能更好?和安道尔一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!