Getting a nicely formatted timestamp without lots of overhead?
- by Brad Hein
In my app I have a textView which contains real-time messages from my app, as things happen, messages get printed to this text box. Each message is time-stamped with HH:MM:SS.
Up to now, I had also been chasing what seemed to be a memory leak, but as it turns out, it's just my time-stamp formatting method (see below), It apparently produces thousands of objects that later get gc'd. For 1-10 messages per second, I was seeing 500k-2MB of garbage collected every second by the GC while this method was in place. After removing it, no more garbage problem (its back to a nice interval of about 30 seconds, and only a few k of junk typically)
So I'm looking for a new, more lightweight method for producing a HH:MM:SS timestamp string :)
Old code:
/**
* Returns a string containing the current time stamp.
* @return - a string.
*/
public static String currentTimeStamp() {
String ret = "";
Date d = new Date();
SimpleDateFormat timeStampFormatter = new SimpleDateFormat("hh:mm:ss");
ret = timeStampFormatter.format(d);
return ret;
}