Performance difference between several conditions in an IF or multiple IF's separately?

9

During a change in a source code, I came across the following situation, developed by another developer:

if ( booleano1 || booleano2 || booleano3 )
{
    if( booleano1 )
    {
        //faz algo
    }

    if( booleano2 )
    {
        //faz algo
    }

    if( booleano3 )
    {
        //faz algo
    }
}

Clearly, the developer's intention was to verify that one of the conditions was true before performing the 3 if separately. The only justification I could find to have been implemented in this way would be a (insignificant?) Gain in performance. So, my question is: is there any performance improvement by using multiple conditions on the same if compared to implementing multiple if separately?

    
asked by anonymous 03.12.2015 / 12:54

2 answers

7

This code certainly performs less than it should. There is no reason for the% outermost% to exist. It does not change any logic, or there is gain. On the contrary, it will certainly make redundant comparisons.

If there was code inside this if beyond the 3% internal%, then there would even be some logical sense.

If they were separated, that is, if you were comparing only the% of external% with the set of internal%% of internal executing separately, it would be difficult to compare because they would be performing something totally different. The if with relational operators will execute once if one of them is true. If you put the three if s each of them will be executed depending on the condition of each one.

If they do not do the same thing, that is, if they do not produce the same result, they can not be compared.

If there were a situation where they could, the gain would be minimal or non-existent. It could be up to it to depend on the compiler (even its version). So it is not something that can be affirmed. What is worth in one day may not be worth in the other.

Do not worry about it.

    
03.12.2015 / 14:13
1

Performance gain would be insignificant for your case. Excessive use of IFs is not recommended as it makes your code difficult to read and maintain, so it is not good practice. It can increase the complexity of the code, increase the difficulty in understanding and the time to do future maintenance.

Source: Why in some situations ifs are considered bad?

    
03.12.2015 / 13:15