Whenever you allocate a new array in C# with
new T[length]
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.
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; }
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.
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?
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.
Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.
You initialize an array variable by including an array literal in a New clause and specifying the initial values of the array. You can either specify the type or allow it to be inferred from the values in the array literal.
There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.
you can initialize an array with a constant value in O(1) time. but it requires extra memory. Actually a better algorithm is known, such that the extra 2n memory words are not needed anymore.
Similar to Dan's answer but without the need of using collections:
int[] myArray = Enumerable.Repeat(-1, 100).ToArray();
It's not redundant.
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With