C# Int32.与(intx)性能进行比较
以下各项是否存在任何性能问题(例如,执行装箱)C# Int32.与(intx)性能进行比较,c#,performance,boxing,C#,Performance,Boxing,以下各项是否存在任何性能问题(例如,执行装箱) 一些进一步的信息。应用程序应该是软实时的,因此使用C#可能是一个奇怪的选择。但是,这不是我能做到的。因为Int32定义了两个重载,一个接受int,另一个接受对象。在上面的示例中,将调用前者。如果必须调用后者,则会发生拳击。现在是每个人最喜欢的游戏节目:盒子还是没有盒子 public string DoIntToString(int anInt) { return anInt.ToString(); } 框或无框?让我们去IL: IL_00
一些进一步的信息。应用程序应该是软实时的,因此使用C#可能是一个奇怪的选择。但是,这不是我能做到的。因为Int32定义了两个重载,一个接受
int
,另一个接受对象
。在上面的示例中,将调用前者。如果必须调用后者,则会发生拳击。现在是每个人最喜欢的游戏节目:盒子还是没有盒子
public string DoIntToString(int anInt)
{
return anInt.ToString();
}
框或无框?让我们去IL:
IL_0001: ldarga.s anInt
IL_0003: call instance string [mscorlib]System.Int32::ToString()
IL_0001: ldarg.0
IL_0002: box [mscorlib]System.Int32
IL_0007: call instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()
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)
无框ToString()
是object
上的virtual
方法,被int
覆盖。由于struct
s不能参与非接口继承,编译器知道不存在int
的子类,可以直接生成对int
版本的ToString()
的调用
框或无框?让我们去IL:
IL_0001: ldarga.s anInt
IL_0003: call instance string [mscorlib]System.Int32::ToString()
IL_0001: ldarg.0
IL_0002: box [mscorlib]System.Int32
IL_0007: call instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()
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)
框GetType()
在object
上不是virtual
,因此该方法没有int
版本。必须将参数装箱,并对新装箱的对象进行调用
框或无框?让我们去IL:
IL_0001: ldarga.s anInt
IL_0003: call instance string [mscorlib]System.Int32::ToString()
IL_0001: ldarg.0
IL_0002: box [mscorlib]System.Int32
IL_0007: call instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()
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)
无框。尽管ToString(IFormattable)
是IFormatProvider
接口的一个实现,但调用本身直接针对int
。出于与第一种方法相同的原因,不需要方框
因此,对于最后一轮,我们有您的方法:
public int CompareIntValues(int left, int right)
{
return left.CompareTo(right);
}
知道
CompareTo(int)
是IComparable
的隐式实现,您可以打电话:BOX或NO-BOX?此代码是否真的存在性能问题?如果不是,您就是在进行微优化。我不确定,因为CompareTo实现了IComparable,但除非在一秒钟内多次调用CompareIntValues,否则这不应该是一个问题。同意Oded的观点,如果您关心此上下文中的性能,您可能应该使用较低级别的语言。老实说,我还没有分析代码。但是,这在性能关键型代码中被多次调用。@Jack:不幸的是,这不是我的决定,但你的观点被采纳了。对于这个天真的后续问题,我深表歉意,但是left
没有装箱,是吗?@Rob-不,也不会装箱。结构类型无法实现GetType()有什么特别的原因吗作为一个静态函数(每个结构类型一个定义),它只返回类型的适当实例?根据我的理解,即使像“returnnewkeyvaluepair.GetType()”这样的东西,在T和U上通用的例程中运行,也将是一个常量,因为T和U的每一个不同组合都会导致该例程的一个单独版本被JITted。它也是吗?