In Java there can be two ways to call a method:
Instantiating and storing the object before calling the method.
Foo foo = new Foo();
foo.method();
Instantiating and directly calling a method
new Foo().method();
For cases where you would end up using foo
again it makese sense to go with the first approach.
However, let's say we know that atleast for the current requirement foo
is only used once to call method
and never again. Which of the options is more suited and why?
I understand that the response can be very subjective, hence I am not looking for reasons such as shorter code, readability, etc (feel free to add them if you want to though). Instead, I am primarily looking for arguments based on performance, memory requirements, garbage collection, etc even if the difference is negligible.
This question has been asked before however I couldn't find any that discusses the above arguments.