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?
To be clear, Calendar is not actually a singleton. Calendar.getInstance() returns a new object each time you call it.
This means that the answer to your question depends on whether or not the functions getSomething() and getBar() have side effects that cause foo to store the new Calendar instance. In general, good programming practices dictate that this won't be the case.
EDIT: However, each time you call Calendar.getInstance() you could end up with a different date. This may be an important detail depending on what your functions are doing.
EDIT 2: it also depends on how often you do the above process. As another answer pointed out, instantiating Calendar objects can be intensive. If you only do it twice, then it doesn't matter if you cache it. If you do this very often, then you may consider changing your approach or doing some caching.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With