直接数组初始化一个恒定值 [英] Direct array initialization with a constant value
问题描述
当你分配在C#中一个新的阵列
Whenever you allocate a new array in C# with
new T[length]
数组项设置为吨默认这就是空
的情况下 T
是一个引用类型或 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.
在我来说,我要初始化与的Int32
数组值-1:
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循环通过新分配的存储器,并设置所有条目为默认(INT)= 0。在此之后,我的code设置的所有项为-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(值,长度).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可以检查你不会使数组可见别处结束初始化之前,但它是一个复杂的检查,以避免pretty简单的抹这种存储区。
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屋!