gpt4 book ai didi

c# - Int32.CompareTo(int x) 性能

转载 作者:太空狗 更新时间:2023-10-29 17:37:11 25 4
gpt4 key购买 nike

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

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

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

最佳答案

是时候播放大家最喜欢的游戏节目了: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()

没有盒子ToString()virtual object 上的方法被 int 覆盖.自 struct s不能参与非接口(interface)继承,编译器知道没有int的子类, 并且可以生成对 int 的调用ToString() 的版本直接。


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()

盒子GetType() 不是 virtualobject , 所以没有 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)

没有盒子。尽管ToString(IFormattable)IFormatProvider 的一个实现接口(interface),调用本身是直接针对 int 进行的.同第一种方法一样,不需要盒子。


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

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

知道CompareTo(int)IComparable<int> 的隐式实现,你做出决定:BOX 还是 NO BOX

关于c# - Int32.CompareTo(int x) 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7162322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com