Should I create a new array or use array.clear?

I have an array of data that is reset to zero from time to time. To do this, you need to create an instance of a new array or use the Array.Clear method?

For instance,

int workingSet = new int[5000];

// Other code here

workingSet = new int[5000];
// or
Array.Clear(workingSet, 0, 5000);
+4
source share
3 answers

When you create a new array instead of the old, C # will be:

  • Make the old array suitable for garbage collection and eventually free it
  • Select a new array
  • Fill the new array with zeros.

When you store the old array, C # will

  • Fill the old array with zeros.

Other things being equal, the second approach is more effective.

+7
source

, Clear(), , .

+2

Array brightness usually has better performance when you have a large array ... I mean thousands of elements. Otherwise, for small arrays, just use the new ones. If you use this array in other places in your code, for example. between threads, you should use clear to make sure everythread will work with a zero / default array

you can easily check it yourself using any stopwatch mechanism or profiling tools

+1
source

All Articles