Android

SimpleDateFormat can be slow

By August 23, 2011November 5th, 2020No Comments

EDIT: Actually the contents of this post are only 1/4 correct. It’s all right to use the default locale if the date you are formatting does not contain any locale specific strings (i.e. an ISO date) however if it does contain locale specific strings it’s a good idea to use the Locale.en_US which should be cached along with Locale.getDefault() in future iterations of the Android OS.

When we were testing some Andromo made apps we seeing the following lines creep up in our logfile:

08-23 15:40:44.342: INFO/Resources(4152): Loaded time zone names for en_US in 282ms.

In some instances the time amount was creeping up to 800ms and a few times it was over one second. As you can probably guess that amount of time in the UI thread resulted in some janky apps.

We knew that the problem had to do with time zones but try as we might we couldn’t find the issue. That was until we found Android Issue 3147. This was happening both on a 2.1 phone device and on a 3.0 Honeycomb device, so I’m not sure how fixed the issue is yet.

But the issue did point us in the right direction: the default locale.

In the end we switched from using the following code to parse dates (which uses the US locale for the date formatting):

new SimpleDateFormat(pattern, Locale.US);

To the following:

new SimpleDateFormat(pattern, Locale.getDefault());

Which uses the user’s preferred locale for the date formatting. Bye-bye janky date parsing.

So that little switch sped our test apps up a metric tonne, and we ended up with code that’s actually more correct.

Maybe this will help other Android programmers searching for google results in the future.

Edit:

If you are interested in what the dates look like (or skeptical) in different locales here are three examples: