Вопрос

I usually build my function this way

public MyObject getMyObject(){
   MyObject myObject = new MyObject()
   return myObject;
}

And wonder if doing it this way is "better" in term of performance or in other term.. How do you do it ?

public MyObject getMyObject(){
   return new MyObject()
}

The example is in Java but it could be any other languages

Thank you

Это было полезно?

Решение

There is a difference in the generated bytecode. You can see the bytecode with javap -c MyObject.class.

the first one does this:

0: new
3: dup
4: invokespecial
7: astore_1
8: aload_1
9: areturn

The second one does this:

0: new
3: dup
4: invokespecial
7: areturn

The main reasoning however, should be readability and not micro-optimization. In this case I think readability and micro-optimization happen to coincide.

Другие советы

The first way of doing it create a reference to the object that won't be used anymore after the return.

The second way do not creates that reference, and so you can save a bit of memory (a really tiny).

The best criteria is the readability of the code. To me the second solution is more consice and clearer, but it is up to you.

There is no sense in having a myObject variable declared, as it will never be used. To keep the code readable and short, I prefer the second option.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top