Which one is faster, powerfull and reliable. And why ?
int.Parse()
int.TryParse()
Convert.ToInt32()
Go read this ("Performance Profiling Parse vs. TryParse vs. ConvertTo") for much add'l info.
If you are unsure if the string is parsable, then int.TryParse()
will be MUCH faster than either of the others and catching the exceptions.
Convert.Int32()
calls Int32.Parse()
with an extra check for null, so which is why Int32.Parse()
might be a tad faster.Convert.Int32()
will be faster (it catches the null before Int32.Parse()
has to deal with it).
Int32.Parse()
calls Number.ParseInt32()
internally which throws Exceptions when a number can't be parsed.
Int32.TryParse()
calls Number.TryParseInt32()
internally which has similar code to Number.ParseInt32()
but instead of throwing Exceptions it simply returns false...which introduces less overhead.
Considering all those variables, my guess would be that Int32.TryParse()
will give you the fastest results for non-null values. If there's a chance the majority of the calls could contain nulls, I would say Convert.Int32()
would perform better.
...all that brought to you by the power of .NET Reflector.
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