Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c#

I have an array of data that gets zeroed out from time to time. To do that, should I instantiate 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);
like image 384
Benjamin Chambers Avatar asked Mar 20 '15 20:03

Benjamin Chambers


People also ask

What does array clear do?

Clear(Array)Clears the contents of an array.

Which is more efficient array or list?

The array is faster in case of access to an element while List is faster in case of adding/deleting an element from the collection.

When would an array be a better choice than a list?

Arrays can store data very compactly and are more efficient for storing large amounts of data. Arrays are great for numerical operations; lists cannot directly handle math operations. For example, you can divide each element of an array by the same number with just one line of code.

Which is better array or list?

An array is faster than a list in python since all the elements stored in an array are homogeneous i.e., they have the same data type whereas a list contains heterogeneous elements.


1 Answers

When you make a new array instead of an old one, C# will:

  1. Make the old array eligible for garbage collection, and eventually deallocate it
  2. Allocate a new array
  3. Fill the new array with zeros.

When you keep an old array, C# will

  1. Fill the old array with zeros.

Everything else being equal, the second approach is more efficient.

like image 141
Sergey Kalinichenko Avatar answered Sep 20 '22 11:09

Sergey Kalinichenko