Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better for performance? And vs AndAlso

Tags:

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?

like image 859
Curtis Avatar asked Jul 15 '11 09:07

Curtis


1 Answers

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

like image 128
Binary Worrier Avatar answered Oct 06 '22 19:10

Binary Worrier