To test Buffer.BlockCopy further, we benchmarked it on a 1000-element array. We compare it with the C# Array.Copy method.
using System;
using System.Diagnostics;
class Program
{
static byte[] GetSourceArray()
{
// Populate data.
var result = new byte[1000];
result[0] = 100;
result[999] = 1;
return result;
}
static bool IsValidData(byte[] data)
{
// Test data.
return data[0] == 100 &&
data[999] == 1;
}
const int _max = 10000000;
static void Main()
{
const int size = 1000;
byte[] source = GetSourceArray();
byte[] target = new byte[size];
// Version 1: use Buffer.BlockCopy.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
Buffer.BlockCopy(source, 0, target, 0, size);
if (!IsValidData(target))
{
return;
}
}
s1.Stop();
// Reset.
source = GetSourceArray();
target = new byte[size];
// Version 2: use Array.Copy.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
Array.Copy(source, target, size);
if (!IsValidData(target))
{
return;
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
}
}
23.49 ns Buffer.BlockCopy
24.56 ns Array.Copy