使用常量值直接初始化数组 [英] Direct array initialization with a constant value

查看:66
本文介绍了使用常量值直接初始化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当你用

new T[length]

数组条目设置为 T 的默认值.对于 T 是引用类型或 的默认构造函数的结果的情况,即 null>T,如果 T 是值类型.

the array entries are set to the default of T. That is null for the case that T is a reference type or the result of the default constructor of T, if T is a value type.

在我的例子中,我想用值 -1 初始化一个 Int32 数组:

In my case i want to initialize an Int32 array with the value -1:

var myArray = new int[100];
for (int i=0; i<myArray.Length; i++) { myArray[i] = -1; }

因此,在为数组保留内存后,CLR 会遍历新分配的内存并将所有条目设置为 default(int) = 0.之后,我的代码将所有条目设置为 -1.

So after the memory is reserved for the array, the CLR loops over the newly allocated memory and sets all entries to default(int) = 0. After that, my code sets all entries to -1.

这使得初始化变得多余.JIT 是否检测到这一点并忽略初始化为 0,如果没有,有没有办法用自定义值直接初始化一部分内存?

That makes the initialization redundant. Does the JIT detect this and neglects the initialization to 0 and if not, is there a way to directly initialize a portion of memory with a custom value?

参考C#数组初始化——非默认值, 使用 Enumerable.Repeat(value, length).ToArray() 是不行的,因为 Enumerable.ToArray 分配一个新数组,然后将值复制到它.>

Referring to C# Array initialization - with non-default value , using Enumerable.Repeat(value, length).ToArray() is no option, because Enumerable.ToArray allocates a new array and copies the values to it afterwards.

推荐答案

不是多余的.

假设在初始化循环期间抛出异常.如果 CLR 没有先清除内存,您可能能够看到"原始未初始化的内存,这是一个非常糟糕的主意,尤其是从安全角度来看.这就是 CLR 保证任何新分配的内存都被擦除为 0 位模式的原因.

Suppose an exception is thrown during your initialization loop. If the CLR hasn't cleared the memory first, you might be able to "see" the original uninitialized memory, which is a very bad idea, particularly from a security standpoint. That's why the CLR guarantees that any newly allocated memory is wiped to a 0 bit pattern.

顺便说一下,同样的论点也适用于对象中的字段.

The same argument holds for fields in an object, by the way.

我想在这两种情况下,CLR 都可以在完成初始化之前检查您不会在其他地方使数组可见,但这是一项复杂的检查,以避免非常简单的擦除该内存区域".

I suppose in both cases the CLR could check that you're not going to make the array visible elsewhere before finishing initialization, but it's a complicated check to avoid a pretty simple "wipe this area of memory".

这篇关于使用常量值直接初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆