I was wondering if there are any speed advantage to doing case B vs case A (or vice versa) in the following:
bool test1(){
// Check something, return true/false
}
bool test2(){
// Check something, return true/false
}
Case A
if(test1() && test2()){
//execute XYZ
}
Case B
if(test1()){
if(test2()){
//execute XYZ
}
}
I mean, if the routines involved in test1()
and test2()
take some time to execute, then intuitively some people may think that Case B may run faster, since test2()
would only get executed if test 1 is true, or is the compiler smart enough to determine, within the logical sequence of Case A, that as soon as test1(...)
fails, then test2(...)
need not be checked?
Perhaps the above are equivalent, can someone let me know...
is the compiler smart enough to determine
yes it is, this is called Short-circuit evaluation, and works with &&
, ||
and ?
operators (unless you overload them), as described in the standard in paragraphs 5.14, 5.15 and 5.16.
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