Monday, November 28, 2011

Comparing Date Formatting Options

Since Java's SimpleDateFormat object isn't thread-safe and synchronizing it in a production application is a bad idea, I've looked into a few alternatives:
1) Create a new SimpleDateFormat object each time we wish to parse a string into a date
2) Create a single SimpleDateFormat object per thread
3) Use the Joda Time library do format dates

I've run two tests on six methods of parsing text:
1) One instance of SimpleDateFormat called many times
2) One static instance of SimpleDateFormat called many times
3) Many instances of SimpleDateFormat called once each
4) One instance of DateTimeFormatter (JodaTime) called many times
5) One static instance of DateTimeFormatter (Joda Time) called many times
6) Many instances of DateTimeFormatter (Joda Time) called once each

The two tests are:
a) 1 formatter x 10,000 parses
b) 10,000 formatters x 2 parses

Test a:
1a) 23 ms.
2a) 28 ms.
3a) 198 ms.
4a) 9 ms.
5a) 10 ms.
6a) 11 ms.

Test b:
1b) 24 ms.
2b) 24 ms.
3b) 304 ms.
4b) 54 ms.
5b) 12 ms.
6b) 9 ms.

Option 1 is the control group because it represents the status-quo (and it's not usable since it doesn't work properly in a multi-threaded environment).  Option 3 is clearly out since it has the worst performance on both metrics.  Options 5 and 6 are both appealing since they both perform well on the tests.


I've chosen to go with option 6 because it removes any concerns abouth multi-threading (though Joda Time doesn't have many).