Which of the following code is fastest/best practice for converting some object x?
int myInt = (int)x;
or
int myInt = Convert.T
Extending the test of Eric Cosky by alternatives from Sam Allen, i found that if you know that your string is a valid integer, then parsing it by yourself is much faster.
I extended the test by the following cases:
timer1000.Measure("IntParseFast", 10, delegate
{
result = Misc.IntParseFast(strInput);
});
timer1000.Measure("IntParseUnsafe", 10, delegate
{
result = Misc.IntParseUnsafe(strInput);
});
With the following implementations:
public static int IntParseFast(string value)
{
int result = 0;
int length = value.Length;
for (int i = 0; i < length; i++)
{
result = 10 * result + (value[i] - 48);
}
return result;
}
public unsafe static int IntParseUnsafe(string value)
{
int result = 0;
fixed (char* v = value)
{
char* str = v;
while (*str != '\0')
{
result = 10 * result + (*str - 48);
str++;
}
}
return result;
}
I get the following results:
IntCaint.Parse 5,495
IntCaConvert.ToInt32 5,653
IntCaIntParseFast 1,154
IntCaIntParseUnsafe 1,245