Tuesday, July 24, 2007

Use System.currentTimeMillis() instead of Date or Calendar

Always try to use System.currentTimeMillis() instead of java.util.Date or java.util.Calendar.

Why?

Because of performance. Date and Calendar internally calls System.currentTimeMillis(). So, why not use it directly?

A BAD example:

long currentTime = Calendar.getInstance().getTimeInMillis();
So, what does Calendar.getInstance() actually do? Following lines are just copied from the source code of jdk1.5:
public static Calendar getInstance()
{
Calendar cal = createCalendar(TimeZone.getDefaultRef(),
Locale.getDefault());
cal.sharedZone = true;
return cal;
}

private static Calendar createCalendar(TimeZone zone,
Locale aLocale)
{
if ("th".equals(aLocale.getLanguage()) &&
("TH".equals(aLocale.getCountry()))) {
return new sun.util.BuddhistCalendar(zone, aLocale);
}
return new GregorianCalendar(zone, aLocale);
}

public GregorianCalendar(TimeZone zone, Locale aLocale) {
super(zone, aLocale);
gdate = (BaseCalendar.Date) gcal.newCalendarDate(zone);
setTimeInMillis(System.currentTimeMillis());
}
Have you got it? Calendar.getInstance() checks TimeZone, Locale and of course System.currentTimeMillis(). So, it's an expensive operation.

Another bad example:
Date date = new Date(System.currentTimeMillis());
Why is it bad? Because, it should be as simple as:
Date date = new Date();
And, here is the apidoc of default constructor of Date:
Allocates a Date object and initializes it so that
it represents the time at which it was allocated,
measured to the nearest millisecond.
Yet, another bad example:
Date date = Calendar.getInstance().getTime();
Now, when should we use System.currentTimeMillis():
When we need only the millisecond representation of the current time.

When should we use Date: When we need a date object representing the current time.

When should we use Calendar.getInstance(): When we need TimeZone or Locale specific information. Another use of Calender can be for creating constant Date object:
public static final Date INDEPENDENCE_DAY;

static {
Calendar calendar = Calendar.getInstance();
calendar.set(1971, Calendar.MARCH, 26);
INDEPENDENCE_DAY = calendar.getTime();
}

3 comments:

Tingting said...

Helpful. Thanks.

Unknown said...

so if you write the calendar.getTime();
what format is that in ?

I need to convert it to seconds I think so I can perform another method that calculates event date + 180 days more worth in nanoseconds to write to ActiveDirectory the new date since 100-nanosecond intervals since 12:00 AM January 1, 1601

any ideas are helpful thx

Rubel_CSE said...

We feel proud for some of you.. Keep going brother....