Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int32.CompareTo(int x) performance

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.

like image 513
Rob Avatar asked Aug 23 '11 14:08

Rob


2 Answers

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.

like image 124
CodeNaked Avatar answered Oct 30 '22 00:10

CodeNaked


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 structs 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?

like image 43
dlev Avatar answered Oct 30 '22 00:10

dlev