Benchmarking IsNumeric Options
 
Published: 14 Oct 2003
Unedited - Community Contributed
Abstract
Which IsNumeric method should you use? Check this article out to find out!
by J. Ambrose Little
Feedback
Average Rating: 
Views (Total / Last 10 Days): 54535/ 60

Introduction

Originally Published: 11 July 2003

One of the frequently asked questions in various .NET developer venues is "how can I check for a numeric value if I am using C#?" The question itself is not precise because it applies equally to other .NET languages, but those using VB.NET, particularly those with a VB or VBScript background, take the IsNumeric function for granted.  What they and many new .NET developers don't know is that this function is actually contained in Microsoft's Microsoft.VisualBasic.dll assembly, which can be used by any .NET language.  So the comparisons in this article are just as valid for VB.NET programmers as they are for those programming in other languages.

 

Test Details

For this benchmark, I compared six different methods of checking a value to see if it is numeric:

  1. Regular Expression - Uses a simple regular expression (^(\d*\.?\d*)$) that matches any digits (0-9) and allows for one decimal point.
  2. Try ToDouble & Catch - Couches a call to System.Convert.ToDouble inside of a try-catch statement; returns true if no error occurs, false if one does occur.
  3. Try Parse & Catch - Couches a call to System.Double.Parse inside of a try-catch statement; returns true if no error occurs, false if one does occur.
  4. Double.TryParse - Uses the System.Double.TryParse method to see if the input is numeric.  Also returns converted value if successful.
  5. VisualBasic IsNumeric - Uses a call to Microsoft.VisualBasic.Information.IsNumeric to see if the input is numeric.
  6. Incremental Char - Loops through each char of the string, using System.Char.IsNumber to see if each char is numeric.  Also allows for one decimal point by comparing each char to '.'.  Thanks to Dave Wanta for suggesting this method.

The test system is a Dell Inspiron 8500 with a Pentium 4-M 2.2GHz CPU, 1GB DDR PC2100 RAM, and 40GB 5400RPM IDE HD.  The application was built and runs on version 1.1 of the .NET Framework, optimized and without debugging information (default Release configuration in VS.NET).  The test involves calling each method 100,000 times using the given input, clocking the start and end time, and extracting the elapsed time in seconds.  I ran two tests for each method, one using input of a valid decimal number (Figure 1) and one using an input of an invalid string containing both numerals and letters (Figure 2).  Please feel free to download the source and run benchmarks on your own machines.

 

Test Results

(Download Source Here)

Figure 1

As you can see in Figure 1, the differences between the six methods are not that dramatic when there is a valid input. I did find that the Regular Expression tended to slow down with larger inputs, but overall, given that these numbers were produced by 100,000 tries, the time required for each and the difference between each is very insignificant.  The incremental char search has the clear edge of about one tenth of a second.

Figure 2

In Figure 2, we see the trend take a dramatic turn, with both methods using a catch block increasing over tenfold to around nine seconds, which highlights the extra effort involved in catching exceptions.  The other methods are almost identical to their counterparts in the previous test, excepting the Regular Expression, which added a good two tenths of a second.  And again, the incremental char search wins out in raw performance by about a tenth of a second.  You may be thinking that if there were more valid numbers prior to the invalid chars that it would lose the advantage (since it would short circuit later), but I tested into the trillions with about the same performance.

 

Conclusions

So which method should you use?  It depends on the application, and maybe on your choice of language.  With regard to the latter, I simply concede that if you are using the VB.NET IDE, it is very easy to just use IsNumeric, and since it is fast and flexible, it may be the option of choice in that environment.  But even if you are using the VB.NET IDE, you may want to consider using Double.TryParse.

In any case, keep in mind that for the given regular expression and incremental char comparison implementations, the definition of "IsNumeric" is limited to digits with one optional decimal.  If you needed to expand this definition to include, e.g., allowing globalization, allowing signs, allowing scientific notation, etc., you could customize them to meet your definition of what a number is, but I would expect that as you get more flexible with the definition, these methods would start to lose out in raw performance (and simplicity).

Therefore, given the insignificant practical performance difference between the Incremental Char, Double.TryParse, and VisualBasic IsNumeric methods, I would choose either Double.TryParse or VB IsNumeric since their definitions of "IsNumeric" include many common variations not accounted for in the Regular Expression or Incremental Char.  Clearly, using one of the Try-Catch methods is a bad idea due to the terrible performance for bad inputs; only use these if you truly do need to handle the exception. 

For most applications, the best method will be TryParse because it offers the most flexibility in definition, the ability to return the converted value concurrently with the type check, and it is part of the System library, so no extra references or work is needed to use it, no matter what language you choose.  If you find it too cumbersome to use directly (because it offers no overloads), you can always wrap it in a static IsNumeric method that only requires the input to check as a parameter.



User Comments

Title: nfl jerseys cheap   
Name: NIKE NFL jerseys
Date: 2012-07-02 10:11:44 AM
Comment:
http://www.jersey2shop.com
http://www.cheapjersey2store.com
http://www.jerseycaptain.com
http://www.yourjerseyhome.com
We are professional jerseys manufacturer from china,wholesal.cheap nike nfl jerseys, mlb jerseys, nhl jerseys,nba jerseys and shoes
Cheap NFL,NBA,MLB,NHL
,heap jerseys,2012 nike nfl Jerseys,nba jersey and shorts,oklahoma city thunder jersey,official jeremy lin new york knicks jersey,NFL Jerseys Wholesale,blake griffin jersey blue,NFL jerseys For Sale online.All Our Jerseys Are Sewn On and Directly From Chinese Jerseys Factory
,Wholesale cheap jerseys,Cheap mlb jerseys,]Nike NFL Jerseys,Cheap China Wholesae,Wholesale jerseys From China,2012 nike nfl Jerseys,Jerseys From China,,2012 nike nfl Jerseys,Revolution 30 nba jerseys,jersey of nba chicago bulls direk rose ,nfl jerseys,green bay packers jerseys wholesale,Buffalo Bills nike nfl jerseys sale,good supplier soccer jerseys,cool base mlb jerseys,Revolution 30 nba jerseys,2012 stanley cup nhl jersey,
We are professional jerseys manufacturer from china,wholesal.cheap nike nfl jerseys, mlb jerseys, nhl jerseys,nba jerseys and shoes. www.yourjerseyhome.com
Title: Straight to the point   
Name: Fabio C. Rispoli
Date: 2006-08-01 4:16:33 PM
Comment:
Congratulations for the article. Simple and straight to the point.

Thanks.
Title: Mr.   
Name: mike
Date: 2006-04-05 10:30:42 AM
Comment:
double.TryParse is also slower than Incremental Chars.
Title: Gopal   
Name: Ambrose
Date: 2006-03-22 1:19:05 PM
Comment:
Gopal,

It's been a long time that I looked at this, but I seem to recall that the VB code didn't use double.TryParse. Maybe it was updated? Are you looking at v2 because this was written before v2 was in alpha...
Title: Another note   
Name: gopal
Date: 2006-03-22 1:13:08 PM
Comment:
Incremental char returns true for empty strings.
Also, looking at the disassembly code, Visualbasic Isnumeric uses Double.TryParse.
Title: just a note   
Name: E
Date: 2006-02-16 3:37:19 PM
Comment:
I was just noticing that the Incremental Char method returns false for negative numbers. . .
Title: IsNumeric?   
Name: Peter Hartlén
Date: 2005-11-17 3:31:17 AM
Comment:
First of all, I did the test with converting a string to integer. Although the code needed for this was a bit more than I at first expected, the performance overhead (compared to simple TryParse) was not that much. The code I used:

public bool TryParseToInt ( string expression, out int iIntVal )
{
double dVal;
bool bRes;

bRes = double.TryParse(expression,
NumberStyles.Integer,
NumberFormatInfo.CurrentInfo,
out dVal);

if( dVal > Int32.MaxValue || dVal < Int32.MinValue )
{
iIntVal = 0;
bRes = false;
}
else
iIntVal = Convert.ToInt32(dVal);

return bRes;
}

As you can see, this method both tests if the string is a valid integer (Int32), and if so, converts the value using the out parameter.

Regarding your results (compared to mine):

Are you sure the data for VB's IsNumeric is correct? During my tests it shows the same performance as try-catch blocks. I’ve read that IsNumeric uses try/catch itself, so it’s merely a wrapper.

The execution time for the Regular Expression method increases quite dramatically when I increase the length of the input string and the faulty character is at the end.

Also worth mention, I did a test with 1 million strings where 2% where faulty (i.e. non-numbers). The performance between a try-catch block function and a TryParse-based function was negligible. So in the real life (where you won’t find 100% correct nor 100% erroneous data), the result looks quite different!
Title: Have to be careful   
Name: Steve Maier
Date: 2005-11-16 11:38:30 AM
Comment:
One thing to remember tho with the incremental character approach is localization. some places use ',' for the decimal point and '.' for the grouping character. With the Parse and TryParse methods, they can take the culture value and will parse things correctly.
Title: Nice reading!   
Name: Peter Hartlén
Date: 2005-11-16 10:16:27 AM
Comment:
Thanks, this was exactly what I was looking for!

I'm using Compact Framework and for example Int32.TryParse is not available, it would be interesting to see the performance of Double.TryParse (using NumberFormat.Integer), with a cast to Int32. I will try this using your code!

Thanks again!
Title: Thanks for the article !   
Name: Deon
Date: 2005-11-02 8:43:18 AM
Comment:
Great article.

Thanks for the effort
Title: Ms.   
Name: Ututu
Date: 2005-08-09 12:32:04 PM
Comment:
Very good article, thanks a lot.
Title: Try-Catch   
Name: J. Ambrose Little
Date: 2005-07-20 8:13:44 AM
Comment:
Try-catch statements are integral to a good program, but they should only be used where they need to be used. There are some good topics on Exception Management in the MSDN Library that you should review to better understand.
Title: Mr.   
Name: Ram Kinkar Pandey
Date: 2005-07-20 5:24:46 AM
Comment:
I was just Looking why using try..catch in ASP.NET is bad idea. This article makes this very clear to me.
Thank you
Title: Mr.   
Name: Linanga Keeba
Date: 2005-07-18 2:23:36 PM
Comment:
The article assisted me very much. Thanks.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-18 11:58:12 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search