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

后端 未结 6 1947
盖世英雄少女心
盖世英雄少女心 2021-01-05 12:24

For example:

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

as opposed to:

<         


        
6条回答
  •  青春惊慌失措
    2021-01-05 13:06

    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.

提交回复
热议问题