How to quickly zero out an array?
Try Array.Clear():
Sets a range of elements in the Array to zero, to
false
, or tonull
(Nothing in Visual Basic), depending on the element type.
C++:
memset(array, 0, array_length_in_bytes);
C++11:
array.fill(0);
C#:
Array.Clear(array, startingIndex, length);
Java:
Arrays.fill(array, value);
UPDATE
Based on the benchmark regarding Array.Clear()
and array[x] = default(T)
performance, we can state that there are two major cases to be considered when zeroing an array:
A) There is an array that is 1..76 items long;
B) There is an array that is 77 or more items long.
So the orange line on the plot represents Array.Clear()
approach.
The blue line on the plot represents array[x] = default(T)
approach (iteration over the array and setting its values to default(T)
).
You can write once a Helper to do this job, like this:
public static class ArrayHelper
{
// Performance-oriented algorithm selection
public static void SelfSetToDefaults<T>(this T[] sourceArray)
{
if (sourceArray.Length <= 76)
{
for (int i = 0; i < sourceArray.Length; i++)
{
sourceArray[i] = default(T);
}
}
else { // 77+
Array.Clear(
array: sourceArray,
index: 0,
length: sourceArray.Length);
}
}
}
Usage:
someArray.SelfSetToDefaults();
Array.Clear(integerArray, 0, integerArray.Length);