gpt4 book ai didi

c# - System.Array 是否对值类型执行装箱?

转载 作者:可可西里 更新时间:2023-11-01 08:43:49 26 4
gpt4 key购买 nike

我最近对 ​​List<> 做了一些粗略的性能测量对比[]对于一系列小型结构。 System.Array 似乎赢得了轻而易举的胜利,所以我选择了它。

我才刚刚意识到 System.Array 包含对象类型,所以用结构填充它肯定会导致装箱吗?

然而,the MSDN entry for System.Array状态:

In the .NET Framework version 2.0, the Array class implements the System.Collections.Generic.IList<T>, System.Collections.Generic.ICollection<T>, and System.Collections.Generic.IEnumerable<T> generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools. As a result, the generic interfaces do not appear in the declaration syntax for the Array class, and there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations).

这是否意味着拳击终究不会发生? (并会解释我的表现结果)

最佳答案

如果使用索引器表示法,则使用数组不会装箱。例如

new int[2];
x=[1]=3;

编译为以下 IL(注意行号是不相关的,因为它们来自其他代码片段)

IL_0011: ldc.i4.2
IL_0012: newarr System.Int32
IL_0017: stfld Int32[] x
IL_001c: ldarg.0
IL_001d: ldfld Int32[] x
IL_0022: ldc.i4.1
IL_0023: ldc.i4.3
IL_0024: stelem.i4

对于不能使用索引器的语言(我真的不知道它们是否存在)在编译时为数组创建了 2 个其他方法。

它创建这些公共(public)方法::

public int Get(int index)
public void Set(int index,int value)

这些方法也不会装箱,通常不能通过 C# 访问。 (不要问我为什么它们是公共(public)方法)。您可以使用 IL 或通过为它们创建委托(delegate)来执行它们。它们速度较慢,因为您被迫执行 callvirt 来调用这些方法。

stelem.* 和 ldelem.* 系列用于处理强类型数组类型的存储。使用泛型时,通常会附加以下前缀 constrainedreadonly使用 T[] 时. stelem.* type 通常不检查类型。例如。使用 stelem.i4比使用 stelem.any Int32 更快除非你用 readonly 作为前缀因为否则它会强制进行类型检查。

现在类型检查对值类型数组完全没用,因为它们不是协变的!

因为运行时生成从零开始的一维数组(称为 SZ_array 或向量类型)类型,所以它们是 native 已知的。

它们有一系列 il 操作码:newarr , stelem.* , ldelem.* , ldlen等等

List<T>类型使用 T[]用于其在 BCL 的 Microsoft 实现中的后备存储。 List<T>不框。无论使用列表还是数组,您都将内容存储在数组中。

关于c# - System.Array 是否对值类型执行装箱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8213887/

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