tags:

views:

544

answers:

4

I am currently doing it in a for loop, and I know in C there is the ZeroMemory API, however that doesn't seem to be available in C#. Nor does the somewhat equivalent Array.fill from Java exist either. I am just wondering if there is an easier/faster way?

+17  A: 

Try Array.Clear():

Sets a range of elements in the Array to zero, to false, or to null (Nothing in Visual Basic), depending on the element type.

Jason Punyon
Man, don't know how I missed this, even looked through all of the members of the Array class.
esac
A: 
Array.Clear(integerArray, 0, integerArray.Length);
Dustin Getz
+6  A: 
  • C++: memset(array,0,sizeof(array))

  • C#: Array.Clear (Array array,int index, int length)

  • Java: Arrays.fill(array, val)

Chap
A: 

Several people have posted answers, then deleted them, saying that in any language a for loop will be equally performant as a memset or FillMemory or whatever.

For example, a compiler might chunk it into 64-bit aligned pieces to take advantage of a 64bit zero assignment instruction, if available. It will take alignment and stuff into consideration. Memset's implementation is certainly not trivial.

one memset.asm. Also see memset-is-faster-than-simple-loop.html.

Never underestimate the infinite deviousness of compiler and standard library writers.

Dustin Getz
I did a test with my for loop vs Array.Clear(). Array.Clear() 2 million times in a loop for a 4K array took 620 ms. The for loop took 13030 ms.
esac