Integer Validation and VC.Net
Catching an exception is an extremely time consuming task, but there's no obvious way to check if a string is actually an integer. And before the visual basic people all say about Microsoft.VisualBasic.Information.IsNumeric this is actually simply a try...catch around a Convert.ToInt32 call.
It's a HORRID use of CPU time programmatically. Some people have suggested that this is simply something you must incur, however due to NumberStyles containing an entry for Integer it needn't be.
Double.TryParse can be used without the risk that the double we'll be getting back will contain anything but a valid integer. This is surpirsingly faster - 100,000 worst case scenarios come to a grand total of 46.875 ms of cpu time used up. A much better overhead. It returns true if the string was an integer and false if not - altering the value of the double passed into it as an out parameter to be the correct amount if it succeeds. Note that the if statements are just there to confuse the compiler so it doesn't optimise out the whole contents of each for loop accordingly.
Model:
using System;
using System.Globalization;
namespace BlogExamples.IntegerValidation
{
class IntegerValidator
{
static void Main(string[] args)
{
Console.WriteLine("Comparison of speed of try..catch checking of integers");
Console.WriteLine("1000 iterations of try...catch Convert.ToInt32()");
DateTime before = DateTime.Now;
for (int i=0; i<1000; i++)
{
try
{
int t = Convert.ToInt32("testing");
if (t>1000)
{
Console.WriteLine("Optimisation cheating");
}
}
catch
{
}
}
TimeSpan duration = DateTime.Now - before;
Console.WriteLine(duration.TotalMilliseconds+" ms total");
CultureInfo MyCultureInfo = new CultureInfo("en-GB");
Console.WriteLine("100000 iterations of Double.TryParse() (to be fair!)");
DateTime before2 = DateTime.Now;
for (int i=0; i<100000; i++)
{
double d = 0;
Double.TryParse("testing", System.Globalization.NumberStyles.Integer,
MyCultureInfo, out d);
if (d>1000)
{
Console.WriteLine("Optimisation cheating");
}
}
TimeSpan duration2 = DateTime.Now - before2;
Console.WriteLine(duration2.TotalMilliseconds+" ms total");
Console.ReadLine();
}
}
}
Have a nice coding!