Which is better for performance? And vs AndAlso

后端 未结 3 477
梦谈多话
梦谈多话 2020-12-30 00:50

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 AndA

相关标签:
3条回答
  • 2020-12-30 01:30

    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.

    0 讨论(0)
  • 2020-12-30 01:38

    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

    0 讨论(0)
  • 2020-12-30 01:43

    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.

    0 讨论(0)
提交回复
热议问题