1

I am writing a little calendar app for Android and I need some functions the Calendar class contains (for example: calculate first day of month, current day of month, day of next month, year of a specific Unix timestamp and so on)

These functions are called frequently and they trigger GC_Concurrent pretty often which causes my app to lag.

This is the way I access the calendar functions:

private static Calendar cal;

public static int getDayOfMonth(long sec) {
    if (cal == null)
        cal = Calendar.getInstance(TimeZone.getDefault());

    //cal.clear();
    cal.setTimeInMillis(sec * 1000L);
    return cal.get(Calendar.DAY_OF_MONTH);
}

Is there a better way to access the functions without producing so much garbage or a better way to calculate the things I need?

durron597
  • 31,968
  • 17
  • 99
  • 158
hndr
  • 59
  • 7
  • Side note: I think your `getDayOfMonth()` should be **synchronized** if you want to ensure that the "singleton" approach works correctly. – GhostCat Apr 17 '15 at 13:16
  • @Jägermeister Actually I think he should be using a `ThreadLocal` over `synchronized`, but yes. – durron597 Apr 17 '15 at 13:20

2 Answers2

1

First question: Have you profiled the code? How certain are you that this is the problem? If you have profiled and you are certain...


Have you tried using Joda Time or Joda Time Android?

Java's default support for dates and times is really terrible, generally speaking.

You can do the same code using Joda time by doing:

public static int getDayOfMonth(long sec) {
  DateTime time = new DateTime(sec * 1000L);
  return time.getDayOfMonth();
}
durron597
  • 31,968
  • 17
  • 99
  • 158
  • I haven't heard of Joda Time, i will have a look for it, thanks! – hndr Apr 17 '15 at 13:23
  • Doesn't your code example produce a lot of garbage aswell if it is executed hundreds of times? – hndr Apr 17 '15 at 13:24
  • Java 1.7 and later is really good at handling short lived objects like this without doing a full GC. There are lots of articles on the subject [but here's one of them](http://www.infoq.com/news/2008/05/g1) – durron597 Apr 17 '15 at 13:27
1

You can't stop stop garbage collection, it is a daemon thread.

It's meant to improve performance; if it's slowing your program, than there likely is a inefficient use of objects/other design flaw causing the garbage collector to have redundant tasks.

I don't want to repeat what you probably already know, but you should look @ this post, it should prove useful.

Android CalendarView slowing down layout

-Eric

Community
  • 1
  • 1
Eric Lang
  • 274
  • 1
  • 2
  • 16