Does int.Parse uses boxing/unboxing or type casting in C#?
What happens when i say
int a = int.Parse("100");
is there any开发者_JS百科 boxing/unboxung or type casting happening inside the Prse method?
There's no boxing or unboxing. Why are you asking? The parsing algorithm is much more expensive than a box/unbox operation so you wouldn't "feel" a performance difference even if there were one.
I don't believe there's any unboxing there. I presume the code uses an int variable and returns it, thus no boxing/unboxing.
Edit: I agree with 280Z28. I just took a look at the code and it's pretty complex. The final value is not boxed as I imagined, but there are some lengthy preprocessing steps to get there so indeed there wouldn't be much change in perfomance even if it were boxed.
BTW, if you didn't know, you can look at the code yourself using Reflector.
Yes. Using Reflector, you can see exactly what's going on. I can't see any boxing, but there are a few 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 this, 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 - so?
To add my bit.
The term/technique of "Unboxing" is ONLY relevant for a boxed value type. Thus, if a value type variable is not boxed(converted to reference type), it can be unboxed.
In your case, you are having a valid reference type value, which has no scope to be unboxed.
精彩评论