JonZarate
JonZarate

Reputation: 871

Is calling Calendar.getInstance() several times efficient?

I need to get the current time several times in an Android App.

I was wondering if calling Calendar.getInstance() was the best implementation, or instead, I could update the given instance (somehow) and make it faster and less expensive (computationally).

Is there any way to update the Calendar instance? Is it faster?

Thank you.

Upvotes: 2

Views: 875

Answers (2)

mvee
mvee

Reputation: 293

I would recommend using either of the below instead of creating lots of new Calendar instances.

System.currentTimeMillis()

System.nanoTime()

If you need a human readable version of the current time, you can then use a Calendar instance to convert from the currentTimeMillis (Long) result, such as below

Long l = 1491812989036L;

Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(l);

System.out.println("year: " + cal.get(Calendar.YEAR));
System.out.println("month: " + cal.get(Calendar.MONTH));
System.out.println("day: " + cal.get(Calendar.DAY_OF_MONTH));

Upvotes: 0

Yaroslav Mytkalyk
Yaroslav Mytkalyk

Reputation: 17115

If you need just current time, you can get it as System.currentTimeMillis(). If you need the Calendar features, no need to call Calendar.getInstance() every time. Instead, you may use existing Calendar reference, and update it by setting the current time, like

calendar.setTimeInMillis(System.currentTimeMillis());

Upvotes: 3

Related Questions