CmdrTallen
CmdrTallen

Reputation: 2282

Any performance difference between int.Parse() and Convert.Toint()?

Is there any significant advantages for converting a string to an integer value between int.Parse() and Convert.ToInt32() ?

string stringInt = "01234";

int iParse = int.Parse(stringInt);

int iConvert = Convert.ToInt32(stringInt);

I found a question asking about casting vs Convert but I think this is different, right?

Upvotes: 30

Views: 18766

Answers (7)

Jason Wang
Jason Wang

Reputation: 1

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.

Upvotes: 0

user3810900
user3810900

Reputation:

There are some performance implications as others have mentioned. If you look at the test code and performance stats from this website:

  • Int.Parse() and Int.TryParse() generally perform faster as the number of conversions you're performing increases.
  • Convert.ToInt() seems to perform best with a low number of conversions
  • The overall fastest way to convert a string to an int (assuming no exceptions) regardless of the number of conversions you need to perform is:

_

y = 0; //the resulting number from the conversion
//loop through every char in the string, summing up the values for the final number
for (int i = 0; i < s[x].Length; i++) 
    y = y * 10 + (s[x][i] - '0');

Upvotes: 1

Vinicius Rocha
Vinicius Rocha

Reputation:

I wrote the code below and the result was that int.parse is slower than convert.toint32.

    static void Main(string[] args) {
        Console.WriteLine(TimeConvertTo());
        Console.WriteLine(TimeParse());
    }

    static TimeSpan TimeConvertTo() {
        TimeSpan start = DateTime.Now.TimeOfDay;
        for (int i = 0; i < 99999999; i++) {
            Convert.ToInt32("01234");
        }
        return DateTime.Now.TimeOfDay.Subtract(start);
    }

    static TimeSpan TimeParse() {
        TimeSpan start = DateTime.Now.TimeOfDay;
        for (int i = 0; i < 99999999; i++) {
            int.Parse("01234");
        }
        return DateTime.Now.TimeOfDay.Subtract(start);
    }

Upvotes: 1

CodingWithSpike
CodingWithSpike

Reputation: 43698

For what its worth:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int iterations = 1000000;
            string val = "01234";

            Console.Write("Run 1: int.Parse() ");
            DateTime start = DateTime.Now;
            DoParse(iterations, val);
            TimeSpan duration = DateTime.Now - start;
            Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms");

            Console.Write("Run 1: Convert.ToInt32() ");
            start = DateTime.Now;
            DoConvert(iterations, val);
            duration = DateTime.Now - start;
            Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms");

            Console.Write("Run 2: int.Parse() ");
            start = DateTime.Now;
            DoParse(iterations, val);
            duration = DateTime.Now - start;
            Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms");

            Console.Write("Run 2: Convert.ToInt32() ");
            start = DateTime.Now;
            DoConvert(iterations, val);
            duration = DateTime.Now - start;
            Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms");

            Console.Write("Run 3: int.Parse() ");
            start = DateTime.Now;
            DoParse(iterations, val);
            duration = DateTime.Now - start;
            Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms");

            Console.Write("Run 3: Convert.ToInt32() ");
            start = DateTime.Now;
            DoConvert(iterations, val);
            duration = DateTime.Now - start;
            Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms");

            Console.ReadKey();
        }

        static void DoParse(int iterations, string val)
        {
            int x;
            for (int i = 0; i < iterations; i++)
            {
                x = int.Parse(val);
            }
        }

        static void DoConvert(int iterations, string val)
        {
            int x;
            for (int i = 0; i < iterations; i++)
            {
                x = Convert.ToInt32(val);
            }
        }

    }
}

Result of 1,000,000 iterations of each:

Run 1: int.Parse() Duration: 312.5ms
Run 1: Convert.ToInt32() Duration: 328.125ms
Run 2: int.Parse() Duration: 296.875ms
Run 2: Convert.ToInt32() Duration: 312.5ms
Run 3: int.Parse() Duration: 312.5ms
Run 3: Convert.ToInt32() Duration: 312.5ms

Upvotes: 17

Rob Windsor
Rob Windsor

Reputation: 6859

When passed a string as a parameter, Convert.ToInt32 calls int.Parse internally. So the only difference is an additional null check.

Here's the code from .NET Reflector

public static int ToInt32(string value)
{
    if (value == null)
    {
        return 0;
    }
    return int.Parse(value, CultureInfo.CurrentCulture);
}

Upvotes: 42

Reed Copsey
Reed Copsey

Reputation: 564333

See this discussion for details.

Convert.ToInt32 won't throw as often (if stringInt == null, it returns 0 instead of throwing an exception), but has a slight bit more overhead since it's doing a few extra checks, then calling int.Parse internally.

Upvotes: 1

Rulas
Rulas

Reputation: 1174

The difference lies in the way both handles NULL value.

When encountered a NULL Value, Convert.ToInt32 returns a value 0. On other hand,Parse is more sensitive and expects a valid value. So it would throw an exception when you pass in a NULL.

Upvotes: 1

Related Questions