Which of the following code is fastest/best practice for converting some object x?
int myInt = (int)x;
or
int myInt = Convert.ToInt32(x);
or
int myInt = Int32.Parse(x);
or in the case of a string 's'
int myInt;
Int32.TryParse(s, out myInt);
I'm curious on which performs the fastest for datatypes which have a method in Convert, not just ints. I just used int as an example.
Edit: This case arose from getting information back from a datatable. Will (int) still work the fastest?
From some testing, when object x =123123123, int performs the fastest, like many have said. When x is a string, Parse runs the fastest (note: cast throws an exception). What I am really curious is how they run when the value is being retrieved in the following way:
foreach(DataRow row in someTable.Rows)
{
myInt = (int)row["some int value"];
myInt2 = Int.Parse(row["some int value"]);
myInt2 = Convert.ToInt32(row["some int value"]);
}
Why don't you just try it a couple of thousand times?
(this goes for all "What is fastest:" questions)
Hmmm, lots of downvotes over the years... I guess I should expand on this answer.
The above statement was made with a degree of flippancy in my youth, however I still agree with its sentiment. It is not worthwhile spending time creating a SO question asking others what they think is faster out of two or three operations that take less than 1ms each.
The fact that one might take a cycle or two longer than the other will almost certainly be negligible in day-to-day usage. And if you ever notice a performance problem in your application when you are converting millions of objects to ints, that's the point where you can profile the actual code, and you'll easily be able to test whether the int conversion is actually the bottleneck.
And whereas today it's the object-int converter, tomorrow maybe you'll think your object-DateTime converter is taking a long time. Would you create another SO question to find out what's the fastest method?
As for your situation (no doubt long since resolved by now), as mentioned in a comment, you are querying a database, so object-int conversion is the least of your worries. If I was you I would use any of the conversion methods you mentioned. If a problem arises I would isolate the call, using a profiler or logging. Then when I notice that object-int conversion is being done a million times and the total time taken by that conversion seems relatively high, I would change to using a different conversion method and re-profile. Pick the conversion method that takes the least time. You could even test this in a separate solution, or even LINQPad, or Powershell etc.