Which of the following code is fastest/best practice for converting some object x?
int myInt = (int)x;
or
int myInt = Convert.T
When I have questions about performance differences between different ways of doing something specific like this, I usually make a new entry in my copy of MeasureIt, a free download from a great MSDN article from Vance Morrison. For more information please refer to the article.
By adding a simple bit of code to MeasureIt, I get the results below which compare the actual timings of the various methods of converting to int. Note the cast from string to int will throw an exception and isn't valid, so I just added the permutations that made sense to me.
Name Median Mean StdDev Min Max Samples IntCasts: Copy [count=1000 scale=10.0] 0.054 0.060 0.014 0.054 0.101 10 IntCasts: Cast Int [count=1000 scale=10.0] 0.059 0.060 0.007 0.054 0.080 10 IntCasts: Cast Object [count=1000 scale=10.0] 0.097 0.100 0.008 0.097 0.122 10 IntCasts: int.Parse [count=1000 scale=10.0] 2.721 3.169 0.850 2.687 5.473 10 IntCasts: Convert.ToInt32 [count=1000 scale=10.0] 3.221 3.258 0.067 3.219 3.418 10
To find the best performance for the various types you are interested in, just extend the code below, which is literally all I had to add to MeasureIt to generate the above table.
static unsafe public void MeasureIntCasts()
{
int result;
int intInput = 1234;
object objInput = 1234;
string strInput = "1234";
timer1000.Measure("Copy", 10, delegate
{
result = intInput;
});
timer1000.Measure("Cast Object", 10, delegate
{
result = (int)objInput;
});
timer1000.Measure("int.Parse", 10, delegate
{
result = int.Parse(strInput);
});
timer1000.Measure("Convert.ToInt32", 10, delegate
{
result = Convert.ToInt32(strInput);
});
}