2

I have the following code snippet as a part of a webservice -

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
    calendar.setTime(date);
    calendar.set(Calendar.MILLISECOND, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    return calendar.getTime();

In this, calendar.set(Calendar.MILLISECOND, 0); seems to be taking 152 milliseconds when the concurrency in the system is high. Is it possible to reduce this? Any performance suggestion would be helpful.

  • 3
    Makes me wonder how you measured that 152 milliseconds. isn't it just a random garbage collection happening at that point? – Imus Apr 21 '17 at 18:43
  • 1
    Out of curiousity, why not `calendar.setTime(date/86400000L*86400000L)`? This would zero out the hours to milliseconds. – Compass Apr 21 '17 at 18:59
  • 2
    @Novaterata Calendar.getInstance() does not return a singleton. It’s a factory method. – VGR Apr 21 '17 at 19:00
  • 1
    Seems like you could skip the 2nd call by using getInstance(TimeZone.getTimeZone("GMT")). and combined with @Compass suggestion you'd save a bit of time. – Novaterata Apr 21 '17 at 19:34
  • @Imus - I have appdynamics installed in the JVM and it provided me with the call stack particularly specifying this line to be taking 152 milliseconds. – Vidya Ramanarayanan Apr 24 '17 at 11:52
  • @Compass - Idea here is to get a java.util.Date instance corresponding to just the values of date, month and year and to strip out the seconds, milisecond, minute, hour from the date value without modifying the actual date. So, divide might not work here. – Vidya Ramanarayanan Apr 24 '17 at 12:53
  • 1
    @ravenswood1411 dividing by 86400000L floors the `Date` to midnight of the same day. – Compass Apr 24 '17 at 14:41
  • 1
    You could try with `java.time.LocalDate` instead of `Calendar`. I have not heard of any performance measurements on it, but wouldn’t be surprised if it performs considerably better. – Ole V.V. May 30 '17 at 20:09

0 Answers0