Does the following have any performance issues (e.g. performing boxing)?
public int CompareIntValues(int left, int right)
{
return left.CompareTo(right);
}
Some further information. The application is supposed to be soft real time, so using C# is perhaps an odd choice. However, that's out of my hands.
There wouldn't be any boxing with what you have as Int32 defines two overloads to CompareTo, one that takes an int
and one that takes an object
. In your example above, the former will be called. If the latter must be called, then boxing would occur.
It's time for everyone's favourite game show: BOX OR NO BOX!
public string DoIntToString(int anInt)
{
return anInt.ToString();
}
BOX or NO BOX? Let's go to the IL:
IL_0001: ldarga.s anInt
IL_0003: call instance string [mscorlib]System.Int32::ToString()
NO BOX. ToString()
is a virtual
method on object
that is overridden by int
. Since struct
s can't participate in non-interface inheritence, the compiler knows that there are no subclasses of int
, and can generate a call to the int
version of ToString()
directly.
static Type DoIntGetType(int anInt)
{
return anInt.GetType();
}
BOX or NO BOX? Let's go to the IL:
IL_0001: ldarg.0
IL_0002: box [mscorlib]System.Int32
IL_0007: call instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()
BOX. GetType()
is not virtual
on object
, so there is no int
version of the method. The argument has to be boxed, and the call is made on the new boxed object.
private static string DoIntToStringIFormattable(int anInt)
{
return anInt.ToString(CultureInfo.CurrentCulture);
}
BOX or NO BOX? Let's go to the IL:
IL_0001: ldarga.s anInt
IL_0003: call class [mscorlib]System.Globalization.CultureInfo [mscorlib]System.Globalization.CultureInfo::get_CurrentCulture()
IL_0008: call instance string [mscorlib]System.Int32::ToString(class [mscorlib]System.IFormatProvider)
NO BOX. Even though ToString(IFormattable)
is an implementation of the IFormatProvider
interface, the call itself is being made directly against the int
. For the same reason as the first method, no box is required.
So for the final round, we have your method:
public int CompareIntValues(int left, int right)
{
return left.CompareTo(right);
}
Knowing that CompareTo(int)
is implicit implementation of IComparable<int>
, you make the call: BOX or NO BOX?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With