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...
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.
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.
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.
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.
They are equally efficient, but B is usually considered to give better readability, especially when used to eliminate several nested conditions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With