For example:
public Person newPerson() {
Person p = new Person(\"Bob\", \"Smith\", 1112223333);
return p;
}
as opposed to:
<
The second option is shorter and easier to read.
I doubt that any decent Java compiler would create less efficient code for the first option though.
No one is not more efficient than the other, the JIT will inline it out to the most efficient at runtime.
Assignment to a temporary variable before returning gives you a chance to do error checking and correction from within your newPerson(). Returning the new call requires the caller of your newPerson() method to catch and recover from errors.
There isn't any difference that would make you chose one over the other in terms of performance.
In general, I'd advice for the latter, and whenever you need to debug this, make a temporary switch to the first (two-line) variant.
In a sane world, they will compile to exactly the same bytecode, so they are identical as far as performance is concerned. Then the only difference is for humans:
Creating a temporary variable makes debugging slightly easier: you can put a breakpoint on the return statement and inspect the value of p
. In the one-line version, this is harder to do.
Doing it in one line eliminates a variable, reducing complexity, making the code slightly easier to read.
In practice, I would write it in one line, and in the worst case I create a temporary variable if I run into the debugging issue. Besides, aren't unit tests supposed to eliminate the need for debugging? :-)
One is not more efficient than the other, but returning created object directly is probably cleaner since you're using less temporary variables. If you must use temporary variables, make it final
and name it appropriately.