gpt4 book ai didi

c# - 类似引用类型变量的装箱和拆箱技术的性能?

转载 作者:太空宇宙 更新时间:2023-11-03 22:42:56 25 4
gpt4 key购买 nike

装箱和拆箱仅为值类型定义。 Source :

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object.

装箱和拆箱的性能是一个昂贵的过程,Source :

Boxing and unboxing are computationally expensive processes. When a value type is boxed, an entirely new object must be created. This can take up to 20 times longer than a simple reference assignment. When unboxing, the casting process can take four times as long as an assignment.

现在,如果我使用 stringstring[],它们是引用类型,我将执行以下操作:

string A;
return (string)(object)A;
// IMP: Here first casting is similar to boxing (though for a reference type), and second casting is similar to unboxing.

同样,

string[] A;
return (string[])(object)A;
// IMP: Here first casting is similar to boxing (though for a reference type), and second casting is similar to unboxing.

与计算量大的值类型不同,我们在这里使用引用类型。对引用类型使用类似装箱/拆箱的技术是否会产生类似的性能影响?

它看起来类似于以下但没有谈论性能影响(如果有的话):

最佳答案

您可能有兴趣知道 C# 编译器完全删除object cast1。你最终得到的是(假设该方法从常量中为 A 赋值,然后得到你显示的代码):

.method private hidebysig static string Thing() cil managed
{
.maxstack 8
L_0000: ldstr "fred"
L_0005: castclass string
L_000a: ret
}

您可能最终会在此处对引用类型进行运行时检查,但如果 JIT 由于 ldstr 而无法静态证明堆栈上的引用,我不会感到惊讶> 已经是 string,因此可以删除它可能考虑为 castclass 操作生成的任何代码。

引用转换是断言(我比编译器更清楚我正在处理的是什么类型)。它们与装箱和拆箱完全不同。


1一般来说,对于引用类型之间的任何向上转换

关于c# - 类似引用类型变量的装箱和拆箱技术的性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51381387/

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