Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if->return vs. if->else efficiency

This may sound like a silly question, and I hesitated to post it, but still: if something needs to run only in a certain condition, which of these is more efficient:

A.

if (condition) {    // do    // things... } 

B.

if (!condition) { return; } // do // things... 
like image 523
Yuval A. Avatar asked Feb 13 '12 20:02

Yuval A.


People also ask

Why is if-else better than if if?

Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.

Is switch case more efficient than if-else?

A switch statement is significantly faster than an if-else ladder if there are many nested if-else's involved. This is due to the creation of a jump table for switch during compilation. As a result, instead of checking which case is satisfied throughout execution, it just decides which case must be completed.

Does if-else affect performance?

In general it will not affect the performance but can cause unexpected behaviour. In terms of Clean Code unneserry if and if-else statements have to be removed for clarity, maintainability, better testing. One case where the performance will be reduced because of unnecessary if statements is in loops.

Why are switch statements faster?

A switch statement works much faster than an equivalent if-else ladder. It's because the compiler generates a jump table for a switch during compilation. As a result, during execution, instead of checking which case is satisfied, it only decides which case has to be executed.


2 Answers

They are equally efficient, but B is usually considered to give better readability, especially when used to eliminate several nested conditions.

like image 151
Klaus Byskov Pedersen Avatar answered Sep 23 '22 05:09

Klaus Byskov Pedersen


Please pick the thing that is most readable. Performance optimizations at this level are hardly ever an issue. Even really performance sensitive parts of frameworks (such as the .NET framework) do not benefit from such an micro optimization.

like image 41
Steven Avatar answered Sep 22 '22 05:09

Steven