linq, ArrayCopy, BlockCopy, marshal 중 BlockCopy가 제일 빠름


테스트 코드

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



출처: http://qiita.com/yu_ka1984/items/c97e0950486e3ecc5642 

저작자 표시
신고
by 흥배 2016.02.05 08:12