I am working with VBA and I am asking this question in order to optimize my code. I have something like this
If reallySmallMethod() And reallyBigMethod() then
'Do some awesome code
End If
So I put the reallySmallMethod() before the reallyBigMethod(), because I figured that Excel would skip the big one if the small one failed. But when I place a break point and step through this if statement, it appears that Excel runs the big method anyways, even if the small method failed. Is it looking for an Or perhaps?
So now I've done this to optimize it
If reallySmallMethod() then
If reallyBigMethod() then
'do some awesome code
End If
End If
It actually seemed like this code was faster when I was working in 'Break mode', but I'm not sure.
Thanks!
What your asking about is commonly called short circuit (Boolean) evaluation (vs. eager evaluation). See https://en.wikipedia.org/wiki/Short-circuit_evaluation. FYI, this property is usually defined in the language (as short circuit or eager) rather than being an optimization the compiler is allowed to do. VBA doesn't have it, or in other words it's boolean operators are defined as eager. You have to write two nested If statements to achieve the desired effect.
It can be noted that short circuit Boolean operators often produces results more expected by programmers than eager. For example, a conditional expression of i < array.length && array [i] ... will work nicely when the intent is to bypass the array indexing of the right hand of the && operator when i is out of array bounds using a short circuit operator. However, a language with an eager boolean operations will still evaluate the right hand expression even though the apparent bounds check has failed.
As Wikipedia notes, some languages define both a short circuit and an eager version of boolean operators, e.g. Visual Basic .NET -- not to be confused with VBA, of course.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With