Tuesday, March 25, 2008

Buffer.BlockCopy Vs Array.Copy

Yes, I do agree that am guilty of being repetitive in my posts. This is yet another comparison of different methods of doing the same thing.

Consider you have two arrays, how do you concatenate them?? Gone are days when you needed to loop through elements and append them. Managed C# has two inbuilt static methods , Array.Copy and Buffer.BlockCopy that helps you in the same.

byte[] c1 = new byte[]{ 2, 3, 4, 5, 6 };
byte[] c2 = new byte[]{ 0,0,0,0,0,22,33,44,55,66};
byte[] c3 = new byte[]{ 0,0,0,0,0,22,33,44,55,66};

Buffer.BlockCopy(c1, 0, c2, 0, 5);

Now the question arises why you need two methods for achieving the same results?? Answer lies in the way both Array.Copy and Buffer.BlockCopy handles the elements while copying.

While Array.Copy copies the elements in an index to index manner, its Buffer Class counterpart uses an offset to offset (byte based) copying method for accomplish its goal.

So what is the impact?? Well, when you are using byte array it has no effect. But what about when you are dealing with int arrays ?? Each Each Int occupies 4 bytes. Lets see the difference in code when above is re-written with int arrays.

int[] c1 = new int[]{ 2, 3, 4, 5, 6 };
int[] c2 = new int[]{ 0,0,0,0,0,22,33,44,55,66};

Buffer.BlockCopy(c1, 0, c2, 0, 20);

Notice that we have changed the number of elements to be copied parameter in the Buffer.BlockCopy Method to 20. This is because each int occupies 4 bytes and hence ( 5 x 4 = 20 bytes ) needs to be copied.