Search code examples
c++performancelogical-operatorsshort-circuiting

Does short circuiting make execution of the program faster, and is analysing which statement to put first in the condition statement worth it?


For instance (Lets say we are talking about C++ if that makes a differnce), In an && operator if I know that one statement will result to 0 more often/has a higher chance then the other statement should I put that on the left side, and the other statement on the right?

Same goes for || operator if I know that one statement will result to 1 more often/has a higher chance then the other statement should I put that on the left side, and the other statement on the right?

Now doing all this would cause a lot of time analysing the program, but if this does speed up execution time for the program is it worth doing it, and is this something that embedded/real-time system programmers look into to speeding up their application if necessary?


Solution

  • First, make sure you are not a victim of premature optimization.

    With that said, make sure that you did everything you could to speedup the bottleneck of your program.


    Doing what you said about the short circuiting may be a good idea in certain cases, but that's heavily depends all your statements.

    For example, if you have something like:

    if(slowFunction() && complexConditionRootsAndExponents && ConditionUsuallyZero)
    

    then you would probably want that last term to be first, wouldn't you?

    However, be careful, things are not always trivial to permute in a logical sequence. Check for example my answer in Why this program printed fork 4 times?, where one can see that short circuit can affect the flow of the execution of the program.


    TL;DR

    In general though, it is rare to get significant speedup by permuting the terms in the conditions. Focus on the bottleneck of your program and tackle that as hard as you can!