Int32.CompareTo(int x)性能

时间:2011-08-23 14:07:45

标签: c# performance boxing

以下是否有任何性能问题(例如执行拳击)?

public int CompareIntValues(int left, int right)
{
    return left.CompareTo(right);
}

一些进一步的信息。该应用程序应该是软实时的,因此使用C#可能是一个奇怪的选择。但是,这不在我手中。

2 个答案:

答案 0 :(得分:12)

现在是每个人最喜欢的游戏节目的时间:BOX OR NO BOX!

public string DoIntToString(int anInt)
{
    return anInt.ToString();
}

BOX NO BOX ?我们去IL:

IL_0001: ldarga.s anInt
IL_0003: call instance string [mscorlib]System.Int32::ToString()

没有BOX ToString()上的virtual object方法被int覆盖。由于struct s不能参与非接口继承,因此编译器知道没有int的子类,并且可以生成对intToString()的调用直接。


static Type DoIntGetType(int anInt)
{
    return anInt.GetType();
}

BOX NO BOX ?我们去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()上的virtual object,因此该方法没有int版本。必须将参数加框,并在新的盒装对象上进行调用。


private static string DoIntToStringIFormattable(int anInt)
{
    return anInt.ToString(CultureInfo.CurrentCulture);
}

BOX NO BOX ?我们去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)

没有BOX 。尽管ToString(IFormattable)IFormatProvider接口的实现,但调用本身直接针对int。出于与第一种方法相同的原因,不需要任何方框。


所以对于最后一轮,我们有你的方法:

public int CompareIntValues(int left, int right)
{
    return left.CompareTo(right);
}

知道CompareTo(int)IComparable<int>的隐式实现,您可以拨打电话: BOX NO BOX

答案 1 :(得分:6)

由于Int32定义了CompareTo的两个重载,一个需要int,一个需要object,所以不会有任何拳击。在上面的示例中,将调用前者。如果必须调用后者,则会发生装箱。