哪个对性能更好? And 与 AndAlso
在编写 If 语句时,我总是在需要时使用 And
,例如:
If 1=1 And 2=2 Then
我唯一使用 AndAlso
的情况是,如果第一个条件不成立,第二个条件将出错,例如:
If Not IsDbNull(Value) AndAlso Value=2 Then
但是,最近我听说 AndAlso
的性能比 And
更好,因为只有当第一个条件为真时才读取第二个条件。
在这种情况下,我应该始终只使用 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 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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,
AndAlso
可能比And
更快,因为如果先前的条件证明为假,它不会评估后续条件。And
是对 Visual Basic 早期版本的回溯。大多数(我犹豫是否要说所有)现代语言都使用布尔运算符来短路不需要严格评估的条件。
例如,C 风格语言的
&&
和运算符都以AndAlso
的形式执行。如果您有大量使用
And
和Or
的代码,请小心,如果第二个条件涉及具有 side 的函数调用,则全局搜索和替换可能会更改现有行为影响。我更喜欢使用
AndAlso
和OrElse
除非您特别需要And
& 提供的功能。或者
Yes,
AndAlso
can be faster thanAnd
, 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 asAndAlso
.Be careful if you've lots of code that use
And
andOr
, 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
andOrElse
unless you specifically require the functionality provided byAnd
&Or
从 C 和 C++ 背景转向 VB(最初是 V5),VB 的
and
和or
没有短路总是很烦人。因此,第二个表达式依赖于第一个表达式的情况总是更难编写。我不希望在大多数情况下看到性能的大幅提升,除非第二个表达式具有显着的开销,否则短路运算符将避免执行它,从而加快速度。
但是,如果第二个表达式是一个很大的开销,那么我会担心只会有时执行的副作用 - 这将使未来的维护变得更加困难,并且可能使正确性更难以维护。
Coming from a C and C++ background into VB (V5 initially) it was always really annoying that VB's
and
andor
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.
当条件也是函数时:
...
...
这里使用
AndAlso
可能是错误的方法,因为这样当 A 和 B 都为 false 时,它只会记录 B。When the conditions are also functions:
...
...
Using
AndAlso
here could be the wrong way to go, because then it will only log B when both A and B are false.