Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one is faster in processing and conversion int.Parse(), int.TryParse(), Convert.Int32()

Tags:

c#

.net

Which one is faster, powerfull and reliable. And why ?

int.Parse()
int.TryParse()
Convert.ToInt32()
like image 994
Shantanu Gupta Avatar asked May 27 '10 15:05

Shantanu Gupta


2 Answers

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.

like image 192
Jaxidian Avatar answered Oct 12 '22 23:10

Jaxidian


Convert.Int32() calls Int32.Parse() with an extra check for null, so Int32.Parse() might be a tad faster. which is why 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.

like image 35
Justin Niessner Avatar answered Oct 12 '22 23:10

Justin Niessner