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

For instance:

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

Unlike:

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

Is it more effective than the other?

+5
source share
6 answers

Assigning a temporary variable before returning gives you the ability to check and correct errors from your newPerson (). Returning a new call requires calling your newPerson () method to detect and recover from errors.

+7
source

There is no difference that would make you choose one from another in terms of performance.

  • For debugging, the first is better - i.e. when you want to track progress or record some information between creation and return.
  • ( ) - .

, , , , () .

+16

, , JIT .

+1

-, . :

: return p. .

, , .

, , . , , ?: -)

+1

, , , , . , final .

0

.

, Java- .

0

All Articles