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

One comment

  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~

Leave a Reply

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