Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to create a new object and return it or create the new object in the return statement?

Tags:

java

For example:

public Person newPerson() {
  Person p = new Person("Bob", "Smith", 1112223333);
  return p;
}

as opposed to:

public Person newPerson() {
  return new Person("Bob", "Smith", 1112223333);
}

Is one more efficient than the other?

like image 978
mheathershaw Avatar asked Feb 25 '10 20:02

mheathershaw


1 Answers

There isn't any difference that would make you chose one over the other in terms of performance.

  • For the sake of debugging, the former is better - i.e. when you want to trace the execution, or log some info between creation and returning.
  • For the sake of readability (but this is subjective) - the latter is better.

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.

like image 59
Bozho Avatar answered Nov 16 '22 02:11

Bozho