tags:

views:

1110

answers:

2

Array.Copy and Buffer.BlockCopy both do the same thing, but BlockCopy is aimed at fast byte-level primitive array copying, whereas Copy is the general-purpose implementation. My question is - under what circumstances should you use BlockCopy? Should you use it at any time when you are copying primitive type arrays, or should you only use it if you're coding for performance? Is there anything inherently dangerous about using Buffer.BlockCopy over Array.Copy?

+3  A: 

Since the parameters to Buffer.BlockCopy are byte-based rather than index-based, you're more likely to screw up your code than if you use Array.Copy, so I would only use Buffer.BlockCopy in a performance-critical section of my code.

MusiGenesis
Completely agree. There's too much room for error with Buffer.BlockCopy. Keep it simple, and don't try to squeeze any juice out of your program until you know where the juice is (profiling).
Skinniest Man
What if you're dealing with a byte[]? Are there any other gotchas with BlockCopy?
thecoop
@thecoop: if you're dealing with a byte[] then it's probably fine to use BlockCopy, unless the definition of "byte" is later changed to something other than a byte, which would probably have a pretty negative effect on other parts of your code anyway. :) The only other potential gotcha is that BlockCopy just does straight bytes, so it doesn't take endianness into account, but this would only come into play on a non-Windows machine, and only if you'd screwed up the code in the first place. Also, there might be some weird difference if you're using mono.
MusiGenesis
+1  A: 

Another example of when it makes sense to use Buffer.BlockCopy() is when you're provided with an array of primitives (say, shorts), and need to convert it to an array of bytes (say, for transmission over a network). I use this method frequently when dealing with audio from the Silverlight AudioSink. It provides the sample as a short[] array, but you need to convert it to a byte[] array when you're building the packet that you submit to Socket.SendAsync(). You could use BitConverter, and iterate through the array one-by-one, but it's a lot faster just to do this:

Buffer.BlockCopy(shortSamples, 0, packetBytes, 0, shortSamples.Length * sizeof(short)).  

And the same trick works in reverse as well:

Buffer.BlockCopy(packetBytes, readPosition, shortSamples, 0, payloadLength);

This is about as close as you get in safe C# to the (void *) sort of memory management that's so common in C and C++.

Ken Smith