Local variables before return statements, does it matter?

SJ19 picture SJ19 · Jul 30, 2015 · Viewed 9.4k times · Source

Sorry if this is a newbie question but I couldn't find an answer for this. Is it better to do this:

int result = number/number2;
return result;

or:

return number/number2;

I know integers use memory so I'm guessing it will slightly decrease performance? But on the other hand it makes stuff clearer, especially when the int/string is a long calculation.

Answer

Fred Porciúncula picture Fred Porciúncula · Jul 30, 2015

Edit: if, like me, you've been using more Kotlin than Java, it'd also be relevant to know that IntelliJ also has an inspection for this in Kotlin:

Variable used only in following return and should be inlined

This inspection reports local variables either used only in the very next return statement or exact copies of other variables. In both cases it's better to inline such a variable.


There is actually a SonarQube rule inherited from PMD called Unnecessary Local Before Return that talks about this. It says:

Avoid unnecessarily creating local variables.

This rule was later replaced by SSLR rule Variables should not be declared and then immediately returned or thrown, which maintains the same position:

Declaring a variable only to immediately return or throw it is a bad practice. Some developers argue that the practice improves code readability, because it enables them to explicitly name what is being returned. However, this variable is an internal implementation detail that is not exposed to the callers of the method. The method name should be sufficient for callers to know exactly what will be returned.

And I totally agree with it.

IntelliJ (or at least Android Studio) also has a warning for this situation:

Variable used only in following return and can be inlined

This inspection reports local variables either used only in the very next return or exact copies of other variables. In both cases it's better to inline such a variable.


I don't think performance is something to worry about at all in this situation. That being said, as @Clashsoft mentioned in his comment, the JIT will most likely inline the variable and you'll end up with the same result either way.