开发者

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

开发者 https://www.devze.com 2022-12-21 02:22 出处:网络
For example: public Person newPerson() { Person p = new Person(\"Bob\", \"Smith\", 1112223333); return p;

For example:

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

as opposed to:

public Person newPerson() {
  return new Person("Bob", "Smi开发者_JS百科th", 1112223333);
}

Is one more efficient than the other?


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.


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.


No one is not more efficient than the other, the JIT will inline it out to the most efficient at runtime.


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? :-)


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消