Which is better for memory management, or any other reason, or are these two scenarios the same:
Calendar currentDateTime = Calendar.getInstance();
int i= foo.getSomething(currentDateTime);
Bar bar= foo.getBar(currentDateTime);
The other code block:
int i= foo.getSomething(Calendar.getInstance());
Bar bar= foo.getBar(Calendar.getInstance());
The general question is, is it better to get an instance of an object, then use that instance when needed, or make the getInstance() call each time when needed.
And, does the answer change if not dealing with a singleton, but making a plain POJO?
For a singleton, it doesn’t make much of a difference. By using a temporary variable, you are saving the overhead of a function call, but nothing more – the same object is being returned each time.
If you are making a POJO, either by calling a constructor or by using an object-creation static method, you are creating a new object. This means that you have the run-time overhead of a function call, as well as the memory overhead of another object being created.
In general, if I am planning on using the same object several times within a method body, I will use a temporary variable. This way, I am doing the same thing whether I need to avoid memory overhead or not, and my code will be more consistent for it.