Shit happens! Yes..Always, Developers like me are used to this but this time, It was not me, Hmmm... I Swear! Lets go back into those bad times and try to make it good.
A little flashback -:
Scenario was, We need full day timings in the interval of 2 seconds in the format of "hh:mm" so we traverse from 9AM to 4PM and convert all the milliseconds in the required format that we need to show on UI.So simple, right.! Just a loop. Developers have left simplistic life decades ago! So after launching this code on Samsung S3, my eyes literally dropped on my table. It was taking around 2.8 seconds time to convert 12600 timestamps into required format which is horrible. After googling & stakoverflowed it, I decided to change Java's default Dateformatting method and let's have a look at libraries of such guys who are calculating this smartly.
Finally got two popular libararies to convert time which are
- Joda Time
- Apache commons lang
I tasted these libraries One by one, and Guess What! got back my dropped eyes. The formatting time was improved fantastically by using both libraries .Here are the statistics taken using Samsung Galaxy S3 & average of 5 readings -:
Main loop of 12600 records -:
private Calendar calendar = Calendar.getInstance();
while (calendar.getTimeInMillis() <= fourPmTimeStamp) {
calendar.add(Calendar.SECOND, 2);
list.add(getFormattedLabel(calendar.getTimeInMillis())); // Here is all SHIT!!
}
Formatting timstamp using different libraries -:
Java's DateTimeFormat
/* This one took 2821 ms, an average of 5 reading */ public String getFormattedLabel(long timeStamp) { return DateFormat.format("hh:mm", timestamp).toString(); }
Apache Commons-lang 2.6
/* This one tasted like pastry & took 937 ms ,an average of 5 reading */ private static FastDateFormat fastdateformat = FastDateFormat.getInstance("hh:mm"); private static Date date = new Date(); public String getFormattedLabel(long timeStamp) { date.setTime(timeStamp); return fastdateformat.format(date); }
Joda-Time v2.3
/* This tasted really Yummy,buttery! It took 612 ms, an average of 5 readings */ private static final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("hh:mm"); private static DateTime dateTime = new DateTime(); public String getFormattedLabel(long timeStamp) { dateTime = dateTime.withMillis(timeStamp); return dateTime.toString(dateTimeFormatter); }
Finally, made our application's life more responsive by Joda-Time.I would like to thanks Joda-Time developers for such optimization in there library and made our life easier. Peace!