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"]); }
Convert. ToInt32 allows null value, it doesn't throw any errors Int. parse does not allow null value, and it throws an ArgumentNullException error.
TOInt32() and Int32. Parse() is efficient? 1) Int32.
Parse() and Int32. TryParse() can only convert strings. Convert. ToInt32() can take any class that implements IConvertible .
Both of the them are slow. If you know the exact format of input string and care about speed, I suggest you write the convert function by yourself.
If x is a boxed int then (int)x
is quickest.
If x is a string but is definitely a valid number then int.Parse(x)
is best
If x is a string but it might not be valid then int.TryParse(x)
is far quicker than a try-catch block.
The difference between Parse and TryParse is negligible in all but the very largest loops.
If you don't know what x is (maybe a string or a boxed int) then Convert.ToInt32(x)
is best.
These generalised rules are also true for all value types with static Parse and TryParse methods.
Fastest != Best Practice!
For example, (int)
is almost certainly the fastest because it's an operator rather than a function call, but it will only work in certain situations.
The best practice is to use the most readable code that won't negatively impact your performance, and 99 times out of 100 an integer conversion isn't driving your app's performance. If it is, use the most appropriate, narrowest conversion you can. Sometimes that's (int)
. Sometimes it's TryParse()
. Sometimes it's Convert.ToInt32()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With