0

Let's say I have this code:

if(number_a==1 && number_b==2) {
doStuff();
}

Will my code run any faster, If i split it up into:

if(number_a==1){
    if(number_b==2){
        doStuff();
    }

}

Or does the computer run the code in the exact order I gave it, checking a first, and instantly moving on if a isn't 1 ? Or is there a chance the computer checks b first, or checks both(even if a isn't 1)?

Firefighter123
  • 59
  • 1
  • 1
  • 4
  • Your question is actually somewhat different from the one it is marked as a duplicate of. On the one hand, there is what the **meaning** of `&&` is: A C implementation is required to produce results **as if** the left side is evaluated first and the right side is evaluated only if needed. This means *side effects* such as increments, assignments, or function calls with effects will not be performed in the right side unless needed. On the other hand, there is the **implementation** of `&&`, especially in regard to performance, as you asked. – Eric Postpischil Dec 29 '18 at 16:14
  • In regard to implementation, a C implementation has a lot of latitude. It is free to evaluate all parts of expressions that do not have any side effects in any order it chooses. If one were optimizing for small code instead of performance, a compiler might choose some “simple” instruction sequence that evaluates everything and uses AND instructions to prepare a final result. Most often, we optimize for performance. With good modern compilers, the two sets of code you show are equivalent: There are no side effects, and a compiler will optimize the evaluation the same way for both. – Eric Postpischil Dec 29 '18 at 16:16

1 Answers1

2

For C this is well-defined: number_a == 1 is evaluated first, and number_b == 2 is evaluated only if the first condition was true (this is called short-circuiting and is important if one of the conditions has a side effect of evaluation).

Cppreference.com confirms this with a more formal restatement:

The logical AND expression has the form lhs && rhs

...

There is a sequence point after the evaluation of lhs. If the result of lhs compares equal to zero, then rhs is not evaluated at all (so-called short-circuit evaluation)

That said, you should not worry about optimization at this level and trust your compiler instead. The difference between these two computations is microscopic and might even be the opposite of what you expect due to microarchitectural effects such as pipelining and other low-level bits.

Instead, focus on writing code that is clean, concise, and readable, while writing algorithms that are efficient in their design. Microoptimization can then be performed if it is absolutely necessary, as a later step.

Community
  • 1
  • 1
nanofarad
  • 40,330
  • 4
  • 86
  • 117