Search code examples
performanceoptimizationconventions

If/ Else, test true first or false first


I have a rather specific question.

Say I am at the end of a function, and am determining whether to return true or false.

I would like to do this using an if/else statement, and have two options: (examples are in pseudocode)

1) Check if worked first:

if(resultVar != error){
    return true;
}else{
    return false;
}

2) Check if it failed first:

if(resultVar == error){
    return false;
}else{
    return true;
}

My question is simple: Which case is better (faster? cleaner?)?

I am really looking at the if/else itself, disregarding that the example is returning (but thanks for the answers)

The function is more likely to want to return true than false.

I realize that these two cases do the exact same thing, but are just 'reversed' in the order of which they do things. I would like to know if either one has any advantage over the other, whether one is ever so slightly faster, or follows a convention more closely, etc.

I also realize that this is extremely nitpicky, I just didn't know if there is any difference, and which would be best (if it matters).

Clarifications:

A comparison needs to be done to return a boolean. The fact that of what the examples are returning is less relevant than how the comparison happens.


Solution

  • The only difference in both examples may be the implementation of the operator. A != operator inverses the operation result. So it adds an overhead, but very small one. The == is a straight comparison.

    But depending on what you plan to do on the If/else, if there is simply assigning a value to a variable, then the conditional ternary operator (?) is faster. For complex multi value decisions, a switch/case is more flexible, but slower.

    This will be faster in your case:

    return (resultVar == error) ? false : true;