Hi,
Today I'll talking about performances between Convert.ToInt32 and Int32.Parse method in order to convert String to Int32.
First of all I wrote a little program to test performances between theses 2 methods which test over 200 000 000 Iterations.
Here is the Test Code
static void Main(string[] args)
{
String StringToConvert = "1234567890";
Int32 ConvertedString = 0;
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 200000000; i++)
{
ConvertedString = Convert.ToInt32(StringToConvert);
}
watch.Stop();
Console.WriteLine("Time Elapsed : " + watch.Elapsed.ToString());
watch.Reset();
watch.Start();
for (int i = 0; i < 200000000; i++)
{
ConvertedString = Int32.Parse(StringToConvert);
}
watch.Stop();
Console.WriteLine("Time Elapsed : " + watch.Elapsed.ToString());
}
This test program bring the following results
| Convert.ToInt32 |
Time Elapsed : 00:01:19.3431743 |
| Int32.Parse |
Time Elapsed : 00:01:16.6393475 |
There is around 3 seconds between these 2 methods ..
So what does this methods do Internaly ?
Here is the code of Int32.Parse Method.
internal static unsafe int ParseInt32(string s, NumberStyles style, NumberFormatInfo info)
{
byte* stackBuffer = stackalloc byte[1 * 0x72];
NumberBuffer number = new NumberBuffer(stackBuffer);
int num = 0;
StringToNumber(s, style, ref number, info, false);
if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
{
if (!HexNumberToInt32(ref number, ref num))
{
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
return num;
}
if (!NumberToInt32(ref number, ref num))
{
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
return num;
}
And here is the code of Convert.ToInt32 method
public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}
return int.Parse(value, CultureInfo.CurrentCulture);
}
Both call the Number.ParseInt32 method !! So why there is that difference ? ... Don't know .. If anyone can tell me why I'm very interested !
Thanks for feedback !
Views(1443)

