Int32.CompareTo(int x) performance

本文关键字:performance int CompareTo Int32 | 更新日期: 2023-09-27 18:06:21

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

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

进一步的信息。应用程序应该是软实时的,所以使用c#可能是一个奇怪的选择。但是,这不是我能控制的。

Int32.CompareTo(int x) performance

大家最喜欢的游戏节目时间到了:盒子还是没有盒子!

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

BOXNO BOX?我们进入IL:

IL_0001: ldarga.s anInt
IL_0003: call instance string [mscorlib]System.Int32::ToString()
<<p> 没有盒子/strong>。ToString()object上被int覆盖的virtual方法。由于struct不能参与非接口继承,编译器知道int没有子类,可以直接生成对ToString()int版本的调用。
static Type DoIntGetType(int anInt)
{
    return anInt.GetType();
}

BOXNO BOX?我们进入IL:

IL_0001: ldarg.0
IL_0002: box [mscorlib]System.Int32
IL_0007: call instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()
盒子

GetType()object上是而不是 virtual,所以没有int版本的方法。实参必须被装箱,并在新的装箱对象上进行调用。


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

BOXNO 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)
<<p> 没有盒子/strong>。尽管ToString(IFormattable)IFormatProvider接口的实现,但调用本身是直接针对int进行的。与第一种方法的原因相同,不需要方框。

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

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

知道CompareTo(int)IComparable<int>的隐式实现,你调用:BOXNO BOX?

不会有任何装箱,因为Int32定义了两个重载到CompareTo,一个接受int,一个接受object。在上面的示例中,将调用前者。如果必须调用后者,则会发生装箱。