a blog for those who code

Thursday 26 June 2014

Fastest way to convert String to Int in C#

Suppose you have a numeric string str and you want to convert that to integer. So, the fastest way to convert is to use Custom method which loops through and converts each character in the numeric string, rather than Convert.ToInt(), Int.TryParse(), Int.Parse().
Below code will show you how to use custom method.

var str = "12356";
var temp = 0;
for(int i = 0; i< str.Length; i++)
temp = temp * 10 + (str[i] - '0');

For less than 2,50,000 iterations it takes less than 0.01 second and every other function takes close to 0.03 second.

No comments:

Post a Comment