Open issues with SimpleDateFormat & a brief introduction to joda-time

By breskeby | February 2, 2009

last week i used the [tag]jprofiler[/tag] to scan our applications for bottlenecks. after just a few minutes i detect that we make really heavy usage of the java.text.SimpleDateFormat class. Using this class in occasional formatting jobs normally causes no problems. But invoking the parse and the format method more than 500.000 times during application startup can definitely cause some performance issues. I identified three problems while working with SimpleDateFormat which are more ore less related to each other:

      [tag]SimpleDateformat[/tag] isn’t threadsafe
      The creation of an SimpleDateFormat is a relativly heavy operation
      the parser methods have a bad performance

my first approach to fix problem #1 and problem #2 was to introduce a SynchronizedFormatter class which implements synchronized methods for parsing and formatting Dates. This SynchronizedFormatter can be called in a static context, so i needn’t so much Formatter objects.

After fixing that, i profiled the app again and still had to handle problem #3. when running an java app with the jprofiler agent, the parse method takes about 50 microseconds. of course thats not the time it would take in operational, mode but nevertheless 500.000 invocations will leave their mark during application startup.

While browsing some java forums i discovered a great library. joda-time replaces the java date and time classes. The homepage listed a lot of reasons why to use their implementation instead of the classes out of the jdk box. Besides the easy to use api and the comprehensive feature set they mention better performance characteristics which definitly match my actual needs.

After replacing all usages of the java.text.SimpleDateFormat by org.joda.time.format.DateTimeFormatter in my app I profiled my app a last time. Since the formatter class of [tag]joda-time[/tag] is threadsafe, I could simply replace my just written SynchronizedFormatter class. The parsing methods of jodas DateTimeFormatter took about 4 microseconds (about ten times faster than the SimpleDateFormat implementation) and the overall startup time of the app reduces dramatically.

If you do lots of formatting, parsing or calculation operations in your java applications you should definitely take a look at the joda-time library! this lib is really impressive!

regards René

Comments