Shiva
Shiva

Reputation: 727

Which is economical for getting Date in String format? creating date objects every time or using date instance thru calendar object

I have a requirement to get current time often and covert that to string and stamp it into a file or as a file name based on business. I have learnt that creating many objects deters the performance.

Now I have two methods to do it, first by creating a Date object every time to get current time.

//Using Date object
SimpleDateFormat sdf = new SimpleDateFormat("MMDDHHmm");
String timeNow = sdf.format(new Date());
System.out.println(timeNow);

Second is to create a Calendar object and get date instance by using getTime() method.

//Using Calendar object to get date instance
SimpleDateFormat sdf = new SimpleDateFormat("MMDDHHmm");
Calendar cal = new GregorianCalendar();
String timeNow = sdf.format(cal.getTime());
System.out.println(timeNow);

which method yields better performance in terms of time and memory used? If there is any other method that'll be more efficient than these two please do share

Upvotes: 1

Views: 262

Answers (3)

AndroidDeveloper
AndroidDeveloper

Reputation: 1

If you need improved speed maybe in synchronization or database handling, the best way is to use JodaTime Library, it is 5 times faster than SimpleDateFormat.

Upvotes: 0

RobF
RobF

Reputation: 2818

Creating a Calendar object is a relatively slow and complex action, it has to compensate for all the oddities that are inherent to dates and times such as timezones, daylight savings etc.

Your best bet is to use the Date object as your first example, see here for a comparison on performance metrics of Date, Calendar and SimpleDateFormat.

Another approach could be to use JodaTime, see here for performance comparison between JodaTime and Calendar. Whilst the difference between Java Date and JodaTime is probably negligible in performance terms, JodaTime is generally agreed to be a better way of handling dates and times. For your purpose, importing JodaTime just for a timestamp may well be overkill though.

Upvotes: 4

Xabster
Xabster

Reputation: 3720

The first one is faster, but it's so little that you should use whatever code looks more appealing to you. The Calendar will create a new Date as well, and base it on the current time, just like your first code except in many more methods calls.

Upvotes: 1

Related Questions