Does an else statement slow compile time/run speed? (In situations where one could be avoided)
coding-style, java, optimization
Solution
It is false optimization. The compiler may actually take longer to compile, with a return from the middle, and any optimizing compiler will produce essentially the same executable code for both forms.
In terms of style, sometimes one style is good, sometimes another. The dangers of the return-immediately style are:
- If there is any common finish-up/clean-up logic at the bottom of the method, it will be missed. It's easy to forget, in a large method, that the logic is there, and it's fairly easy, in a large method, to edit such logic into a method that didn't previously have it. Bugs of this sort can be hard to find.
- Because it essentially eliminates the option of having "clean-up" logic at the bottom of the method, it can lead to a proliferation of logic in the individual `if` legs, creating more clutter than the standard if/then/else.
- It runs counter to good "structured programming" practice.
That said, there are cases where the return-from-the-middle style is a better choice:
- Cases where there are multiple sequential `if` statements, each with a simple body and each capable of ending with return.
- The case of a very brief method where the "fast exit" is natural and fairly evident.
- The case of a "fast exit" (eg, because some data item is nil) very near the top of a longer method.
Problem
On innumerable (well, numerable, but many) occasions, especially within a method/function of a class, I've been in a situation where I want to do a set of operations within a void-return function, but only `if(condition met)`. In most cases, I can see how (assuming that the code works) an `else` statement can be removed altogether by simply returning in the `if` block. Here's a specific example, in case that didn't make sense: With an else statement (how a teacher would show it) ``` private void ifThisDoThat(params){ if(dependenciesNotMet) return; else{ ////DO STUFF HERE... } } ``` Without (more parsimonious) ``` private void ifThisDoThat(params){ if(dependenciesNotMet) return; //Assuming the above does not execute, DO STUFF HERE... } ``` I am thinking that removing the `else` statement, if an optimization at all, would be classified as a micro-optimization, but still figured I would ask for my own edification. In closing: Are there any benefits to using a `return` to remove an `else` block? Does the compiler do extra work if I use an `else` statement? Is there a reason to always use the `else` (in case of errors, or for some other reason)?