manski's blog

.NET – Array.Clear() vs. array[x] = 0 – Performance

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 0 or null).

The two contesters are:

  • array[x] = 0 (iterate over the array and simply set the values to 0)
  • Array.Clear()

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] = 0 is faster.
  • For large arrays, Array.Clear() is faster.
  • 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:

ArrayClearTest.cs

5 comments

  1. TianqiZhang said:

    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~

  2. Andrey-WD said:

    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!

  3. Nick said:

    You definitely should’ve tested Array.Copy and Buffer.BlockCopy. Both methods should be faster than plain index access

  4. booboo said:

    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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.