jump to navigation

How to Over-Analyse December 15, 2008

Posted by Phill in General J2EE.
Tags: , , , ,

Apologies for the random post, but we were having a discussion on a question on StackOverflow about how to detect whether a string is a number in Java.

I posted up a possible WTF solution involving regexes.  (You’ll have to read the original question for all the background). Someone suggested instead using NumberFormat. Jon Skeet replied with a different solution as well.

After all the discussion I thought I’d do a quick speed test. It turned out to be a rather overblown, over-engineered speed test… but it produced some interesting results 🙂

Firstly, the code. I’ve uploaded it on my website so you can check it yourself.

The code tests three methods of checking to see whether a string is a number: using a (basic) regex, using NumberFormat.parse(…), and using the JonSkeet (TM) method. Each method is called 1,000,000 times per test and each test is run five times and then averaged.

These are the results on my machine:

Testing: Regex Tester
2672 2578 2562 2547 2594
Average time: 2590
Testing: NumberFormat Tester
9641 9531 9375 9391 9578
Average time: 9503
Testing: Jon Skeet Tester
235 218 235 234 235
Average time: 231

Using NumberFormat is 3x slower than using a Regex – although NumberFormat will parse a greater range of numbers (i.e. it parses numbers properly rather than using a rather dumb regex). But – Jon Skeet’s method is more than 10x faster than the regex. Ladies and gentlemen, I think we have a clear winner. Jon Skeet FTW! (But then, we all knew that anyway…)

Apologies for this interruption, normal blogging service will resume yada yada yada.

(Edit: I should point out that if you want the “Correct” method of checking whether a String is a number, you should use NumberFormat. This is maintained by Sun and will account for locales etc. Basically it is the canonical way of parsing a number. The regex method is probably good if you just want to check whether a String contains digits in one line of code, quick and dirty. And the Jon Skeet method is if you want correct AND fast, and can shove that method in a utility class somewhere).

%d bloggers like this: