4

In Effective Java Item 5: Avoid creating unnecessary objects

Here Joshua Bloch said Calendar instances are particularly expensive to create. but there was no reason mentioned out there .

My Question is Why is it more expensive than Instance creation of other Classes?

Community
  • 1
  • 1
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
  • 1
    There is a site with exactly this question from the same book - the website explains in some detail why it is expensive: http://cephas.net/blog/2006/02/25/the-cost-of-calendar-object-creation/ – ThePerson Feb 24 '15 at 19:45
  • My recommendation is to look at the source code. There is a lot of stuff happening on Calendar.getInstance() that is mind-boggingly complicated. It is more efficient to use a long if possible. – Necreaux Feb 24 '15 at 19:47
  • @Necreaux `It is more efficient to use a long if possible. ?` What exactly this means – Neeraj Jain Feb 24 '15 at 19:57
  • 1
    The Calendar object is mostly useful for stuff like date arithmetic, outputting etc. If you want it for comparison, timing etc. System.currentTimeMillis() to get a long can be used for that. A long can always be loaded into a Calendar object later or extracted from it too. – Necreaux Feb 24 '15 at 20:00
  • @Necreaux I am currently not concerned about usage , wanted to know the reason about it's expensiveness as it was not clearly mentioned in [Java Docs](http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html) too – Neeraj Jain Feb 24 '15 at 20:08
  • The idea is that if all you need is a way to pass a date-time around, most of the time a long is all you need. A long can hold the number of millis since epoch time, and can be turned into a Calendar when you actually need a localized representation of a date. –  May 15 '15 at 18:23

1 Answers1

0

You actually kinda answered your question in the comments. Unless you want to work with all complexity of Calendar, calculate holidays, week days, time zones, etc then simple long will serve your. Calendar takes a lot of memory (instead of 8 bytes for long) because it has to serve all these conversions, transformations, comparisons, leniency, field manipulation and other functions based on locales. It has a lot fields staring with ERA, DAY_OF_WEEK, DAY_OF_WEEK_IN_MONTH, etc. All of them are used in some actions so performance of the class is much worse then simple long comparison.

Of course you cannot compare to other Classes. Each class serves its own needs and could be much more complex and expensive then Calendar.

Alex
  • 4,457
  • 2
  • 20
  • 59