Does int.Parse use boxing / unboxing or casting type in C #?

What happens when I say

 int a = int.Parse("100");

      

Is there any boxing / unboxung or type of casting happening inside the Prse method?

+2


source to share


4 answers


No boxing or unboxing. Why do you ask? The parser is much more expensive than the box / unbox operation, so you won't "feel" the difference in performance, even if there is one.



+10


source


I don't believe there is no unpacking there. I assume the code is using an int variable and returning it, so there is no boxing / unboxing.

Edit . I agree with 280Z28. I just took a look at the code and it is quite complicated. The final value doesn't fit in the box as I imagined, but there are some lengthy preprocessing steps to get there, so there really wouldn't be much of a performance change even if it were in the box.



By the way, if you didn't know that, you can look at the code yourself using Reflector .

+2


source


Yes. Using Reflector you can see exactly what is going on. I don't see any boxing, but there are several casts, for example:

private static unsafe void StringToNumber(string str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo info, bool parseDecimal)
{
    if (str == null)
    {
        throw new ArgumentNullException("String");
    }
    fixed (char* str2 = ((char*) str))
    {
        char* chPtr = str2;
        char* chPtr2 = chPtr;
        if (!ParseNumber(ref chPtr2, options, ref number, info, parseDecimal) ||
           ((((long) ((chPtr2 - chPtr) / 2)) < str.Length) && //cast
            !TrailingZeros(str, (int) ((long) ((chPtr2 - chPtr) / 2))))) //cast
        {
            throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
        }
    }
}

      

or it happens in a loop:

private static unsafe char* MatchChars(char* p, string str)
{
    fixed (char* str2 = ((char*) str)) //cast
    {
        char* chPtr = str2;
        return MatchChars(p, chPtr);
    }
}

      

The real question is, right?

0


source


To add my beat.

The term / method "Unboxing" ONLY refers to the short value type. Thus, if a variable of a value type does not fit into a cell (converted to a reference type), it can be unpacked.

In your case, you have a valid reference type value that is not unboxable.

0


source







All Articles