Faster Conversions

tinstaafl 1 Tallied Votes 144 Views Share

In a recent discussion these code snippets were developed to replace Convert.ToInt32 and Convert.ToDouble. The person I was helping had a very large number of conversions to do. In our tests, using these 2 routines we were able to do over 1 million conversions in less than half the time. I thought it would be nice to share these with others. I found them quite useful as a class library.

Caveats: There is no validation or exception trapping. I figured that each person using these can decide on their own if they need it.

public static double ToDouble(string input)
        {
            double n = 0;
            double factor = 1;
            double flag = 10;
            int length = input.Length;
            for (int k = 0; k < length; k++)
            {
                char c = input[k];
                if (c == '.')
                    flag = 1;
                else
                {
                    factor *= flag * .1;
                    n = (n * 10) + (int)(c - '0');
                }
            }
            return n * factor;
        }
        public static int ToInt(string input)
        {
            int n1 = 0;
            int length = input.Length;
            for (int k = 0; k < length; k++)
            {
                char c = input[k];
                n1 = (n1 * 10) + (int)(c - '0');
            }
            return n1;
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.