So, yet another performance test for .NET. This time I was checking what’s the fastest way to clear an array (i.e. setting all array members to
The two contesters are:
array[x] = 0(iterate over the array and simply set the values to
Here are some results:
Clearing 5,000,000,000 items per test Array.Clear() - Array size: 5 : 31.564s Array[x] = 0 - Array size: 5 : 4.428s Array.Clear() - Array size: 25 : 7.477s Array[x] = 0 - Array size: 25 : 3.315s Array.Clear() - Array size: 50 : 4.414s Array[x] = 0 - Array size: 50 : 3.629s Array.Clear() - Array size: 100 : 2.571s Array[x] = 0 - Array size: 100 : 3.292s Array.Clear() - Array size: 500 : 0.935s Array[x] = 0 - Array size: 500 : 3.014s Array.Clear() - Array size: 50000 : 0.621s Array[x] = 0 - Array size: 50000 : 2.948s
In each test 5 billion
int array items were cleared (that’s 20 GB). Tests was run first with a small array whose size was increased after each test run. The test were run as Release build.
As you can see:
- For small arrays,
array[x] = 0is faster.
- For large arrays,
They’re about equally fast for array sizes between 50 and 100. (My guess is, somewhere around 75.)
And here’s the source code for this test:
hey man, just read your post, want to say thank you for the experiment! I was optimizing some C# code, switching from array[x] = 0 to Array.Clear() brought me 5% perf bonus, that’s so cool man~
That is your contribution on SO: https://stackoverflow.com/a/43188508/5259296
BTW, the delimiter between those two approaches is 76 items length (1..76 and 77+). Look at the plot.
Thank you for a great benchmark!
Thanks for figuring out the exact number
You definitely should’ve tested Array.Copy and Buffer.BlockCopy. Both methods should be faster than plain index access
The test is flawed because first invocation of Clear() and SetZero() functions will cause these functions to be jit-compiled, and the compilation time is included in results.
You must call these functions at least once before doing the timing round.