What is the main difference between int. Parse() and Convert.Toint32()?

Asked

Viewed 10,850 times

18

In C#, there are two ways (among others) to convert other types to int:

Convert.ToInt32(valor) and Int32.Parse(valor).

What is the main difference between these two forms of conversion?

2 answers

16


The Int32.Parse(valor) only converts content from string. The Convert.ToInt32() has overloads to work with various types. This is the main difference.

But the best way is to see what he looks like internally:

Parse():

public static int Parse(string s)
{
    return System.Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}

internal static unsafe int ParseInt32(string s, NumberStyles style, NumberFormatInfo info)
{
    byte* stackBuffer = stackalloc byte[1 * 0x72];
    NumberBuffer number = new NumberBuffer(stackBuffer);
    int num = 0;
    StringToNumber(s, style, ref number, info, false);
    if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
    {
        if (!HexNumberToInt32(ref number, ref num))
        {
            throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
        }
        return num;
    }
    if (!NumberToInt32(ref number, ref num))
    {
        throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
    }
    return num;
}

Convert():

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

Withdrawn of that OS response.

But you can see the actual source code: Convert.ToInt32() and Parse(). Better still follow on . NET Core (Convert.ToInt32() and Parse()).

Prefer the TryParse()

Related: What is the difference between using (int)variable or Convert.Toint32(variable)?.

Be sure to see: Differences between Parse vs Tryparse.

  • It is worth noting that Convert turns null to 0. This can be an unwanted behavior in many cases, for example where 0 is information and null would be the absence of information. In this situation, tryParse is the option. Imagine, for example, averaging optional values stored in a text file, if used Convert the average will be incorrect as it will convert to zero values that do not exist, bringing the average to a lower value than the real...

12

Playing Int32.Parse() in the Reflector:

public static int Parse(string s)
{
    return System.Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}

Which in turn calls:

internal static unsafe int ParseInt32(string s, NumberStyles style, NumberFormatInfo info)
{
    byte* stackBuffer = stackalloc byte[1 * 0x72];
    NumberBuffer number = new NumberBuffer(stackBuffer);
    int num = 0;
    StringToNumber(s, style, ref number, info, false);
    if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
    {
        if (!HexNumberToInt32(ref number, ref num))
        {
            throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
        }
        return num;
    }
    if (!NumberToInt32(ref number, ref num))
    {
        throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
    }
    return num;
}

Playing Convert.ToInt32() in the Reflector:

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

Use

  • Int32.Parse() is noticeably faster than Convert.ToInt32(), but more insecure. You should use Int32.Parse() when you are sure that the input value is an integer;
  • There is still Int32.TryParse(), which is a little safer. Returns zero if conversion fails and throws no exception;
  • Convert.ToInt32() is a slightly safer envelope of Int32.Parse() (you can tell by the code.

Performance

Still, the fastest way to perform the conversion is by a simple cast:

var inteiro = (int)meuObjeto;

Of course it’s pretty unsafe to do that, but it pays off if, again, you know what’s inside the object is a whole.

For this answer, it is possible to see the Assembly of this cast:

.locals init (
    [0] object x,
    [1] int32 Y)
L_0000: ldc.i4.1 
L_0001: box int32
L_0006: stloc.0 
L_0007: ldloc.0 
L_0008: unbox int32
L_000d: ldobj int32
L_0012: stloc.1 
L_0013: ret

Whereas Convert.ToInt32() generates:

.locals init (
    [0] object x,
    [1] int32 Y)
L_0000: ldc.i4.1 
L_0001: box int32
L_0006: stloc.0 
L_0007: ldloc.0 
L_0008: call object [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::GetObjectValue(object)
L_000d: call int32 [mscorlib]System.Convert::ToInt32(object)
L_0012: stloc.1 
L_0013: ret

This answer has a benchmark complete over all possible assignment modes for an integer. The difference is overwhelming.

  • It is not possible to do cast with string, then the information is incorrect and the comparison makes no sense in this question.

  • You’re right. I switched to object. Thank you!

  • 1

    Okay now, but it still doesn’t make sense to compare the performance of Convert numerical with Parse of string . These are two different entrances. It’s like saying that a Ferrari is faster than the truck, but we’re wondering which loads more loads.

  • 1

    I didn’t understand your ready. The question is about the differences between one and the other.

  • 1

    Compare numerical conversion performance with conversion performance string has no meaning. They do different things. What’s the point of being faster if it doesn’t serve the purpose?

  • I didn’t see anything specifically written about string in the body of the question.

  • It is implied. The Parse only does this.

  • 1

    Please stop finding fault with my answer. This is not being productive.

  • It would be easier for you to solve the defect, but if you don’t want to, ok. At least people can know that there is this problem.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.