Skip to content Skip to sidebar Skip to footer

'if/else' Vs 'if' For Performance And Readability?

I've recently started using Snippet 2 instead of Snippet 1, for basic selection statements. This seems a bit un-conventional, so I wanted to know if there is performance differenc

Solution 1:

Your snippets are the same thing. But I'd use elseif even if I return. It kind of gives me a sense that those if statements are related and helps me with readability.

if ... else also helps in performance, let's say, when you're if-ing the same variable. Why test a condition if the previous one succeeded? elseif it so it won't try again.

It's a matter of design. It depends on what you want to achieve so there's no EXACT BEST way of doing it. It's all a matter of how you need to exit your code block that contains the ifs.


Solution 2:

The Ifs alone mean that all of the conditions can possibly happen - they'll be checked one by one. The chained if-else statements mean that only one of the conditions can actually happen - if one of the conditions get executed, I believe it skips over all of the rest. Most languages support a switch statement as well, which would be somewhat more readable than chaining together a bunch of if-else-if statements. Correct me if I'm wrong, but I believe this applies in every language I've used so far.

Edit: In this particular case (as pointed out by some others below - thank you), all of the conditions cannot happen because of the return statements in each of the if statements. In a more general case though, my explanation still holds.


Solution 3:

It depends on your needs. As a general rule, the more exit points you have to a function, the harder it is to read. That said, there is often benefit of

if(somehting)
{
    // one liner;
    return;
}
if(something else)
{
    // 30 lines of something else.
    return;
}
// catchall

instead of:

if(something)
{
    // one liner;
    return;
}
else if(something else)
{
    // now nested! 30 lines.
    return;
}

Chances are, though, that you could probably make things even easier to read by turning those conditions into their own functions. Wouldn't this be nice:

if(something)
{
    doSomething();
}
else if(something else)
{
    doSomethingElse();
}
else
{
    doJustElse();
}

The benefit of the last one? Succinct, clear, clean, obvious, and a low learning curve.


Solution 4:

If you have too many else if statements then it always better to use switch rather than using if.


Solution 5:

Snippet 1 is going to be better for performance when you don't need case 3 to be satisfied, since the other else if will not be fired. However, if you have a lot of other else if, you should use a switch


Post a Comment for "'if/else' Vs 'if' For Performance And Readability?"