Array Initialization with Explicit Zero-Out vs. Allocation in C#

When I write machine learning code, I often have to zero-out an array many times. In C# I can either explicitly zero-out the array with a for-loop and assign 0.0 values to each cell, or I can reallocate the array using the “new” keyword because in C# all cell values in a type-double array are automatically set to 0.0 when an array is allocated.


So which way is faster? Performance is very tricky and in most situations the only way to be sure is to try things out. I wrote a little demo program with an array that has 100 cells and I zeroed it out 1,000,000 times using each of the two techniques.

I was mildly surprised that the re-allocation technique was faster than the explicit assignment technique. I’m guessing that C# array initialization is highly optimized and perhaps can directly zero-out blocks of memory that correspond to the array.

This entry was posted in Machine Learning. Bookmark the permalink.