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.
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();