What ways of calling methods give me the best performance

What i want to ask is if i do

final Cat c = getBlackCat();
polishCat(c);

Or

polishCat(getBlackCat());

Are those compiled into the same thing ? Whats the best practice ? and what would be the memory wise and cpu wise better ?

Answer

At the bytecode level, you must always explictly store the result of one method invocation to be able to feed it into the next one. You can consider the “nested calls” idiom in Java as just syntactic sugar over that. So yes, the two pieces of code are equivalent.

Which is preferred stylistically is open to debate and there are arguments in favor of either. I favor the argument that each time you explicitly name a thing in your code, it creats an obligation on the part of the reader to remember that name and what it refers to. If the variable is not final then the reader must in addition carefully track all usages of the variable lest there be another assignment somewhere else, even if by accident (for example, using = instead of ==). If you call methods inline, you don’t impose that cognitive load.

Leave a Reply

Your email address will not be published. Required fields are marked *