Edited at

バイト配列の部分コピーの速度のおはなし

More than 1 year has passed since last update.

過去皆さん書いてることだけどね。

わかってることだけど速さ必要なところでサボってlinqで書いちゃいけないよってね(;・∀・)

    class Program

{
const int COUNT = 1000000;
static void Main(string[] args)
{
var basearray = Enumerable.Range(0, 1024).Select(x => (byte) x).ToArray();

var sw = Stopwatch.StartNew();
for (var i = 0; i < COUNT; i++)
{
var buffer = basearray.Skip(20).Take(20).ToArray();
}
sw.Stop();

Console.WriteLine($"linq {sw.ElapsedMilliseconds}ms");

sw = Stopwatch.StartNew();
for (var i = 0; i < COUNT; i++)
{
var buffer = new byte[20];
Array.Copy(basearray, 20, buffer, 0, 20);
}
sw.Stop();

Console.WriteLine($"ArrayCopy {sw.ElapsedMilliseconds}ms");

sw = Stopwatch.StartNew();
for (var i = 0; i < COUNT; i++)
{
var buffer = new byte[20];
Buffer.BlockCopy(basearray, 20, buffer, 0, 20);
}
sw.Stop();

Console.WriteLine($"BlockCopy {sw.ElapsedMilliseconds}ms");

sw = Stopwatch.StartNew();
var ptr = Marshal.AllocCoTaskMem(basearray.Length);
Marshal.Copy(basearray, 0, ptr, basearray.Length);
try
{

for (var i = 0; i < COUNT; i++)
{
var buffer = new byte[20];
Marshal.Copy(ptr + 20, buffer, 0, 20);
}
}
finally
{
Marshal.FreeCoTaskMem(ptr);
}
sw.Stop();

Console.WriteLine($"marshal {sw.ElapsedMilliseconds}ms");

Console.ReadKey();
}

linq 1622ms

ArrayCopy 71ms

BlockCopy 55ms

marshal 62ms