Last active
July 26, 2021 11:15
-
-
Save fraguada/301fe31b939e6889514969cb1bbec37c to your computer and use it in GitHub Desktop.
c# Array copying performance test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// from https://stackoverflow.com/questions/30636113/get-subarray-of-byte/30636227#30636227 | |
// added Buffer.Copy() test | |
// added ArraySegment().ToArray() test | |
public static void Test() | |
{ | |
const int MAX = 1000000; | |
int[] arrByte1 = Enumerable.Range(0, 1000).ToArray(); | |
int[] arrByte2 = new int[500]; | |
Stopwatch sw = new Stopwatch(); | |
// Array.Copy | |
sw.Start(); | |
for (int i = 0; i < MAX; i++) | |
{ | |
Array.Copy(arrByte1, 500, arrByte2, 0, 500); | |
} | |
sw.Stop(); | |
Console.WriteLine("Array.Copy: {0}ms", sw.ElapsedMilliseconds); | |
// Linq | |
sw.Restart(); | |
for (int i = 0; i < MAX; i++) | |
{ | |
arrByte2 = arrByte1.Skip(500).Take(500).ToArray(); | |
} | |
sw.Stop(); | |
Console.WriteLine("Linq: {0}ms", sw.ElapsedMilliseconds); | |
// Buffer.BlockCopy | |
sw.Restart(); | |
for (int i = 0; i < MAX; i++) | |
{ | |
Buffer.BlockCopy(arrByte1, 500, arrByte2, 0, 500); | |
} | |
sw.Stop(); | |
Console.WriteLine("Buffer.BlockCopy: {0}ms", sw.ElapsedMilliseconds); | |
// ArraySegment | |
sw.Restart(); | |
for (int i = 0; i < MAX; i++) | |
{ | |
arrByte2 = new ArraySegment<int>(arrByte1, 500, 500).ToArray(); | |
} | |
sw.Stop(); | |
Console.WriteLine("ArraySegment: {0}ms", sw.ElapsedMilliseconds); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Typical results on W10 VMWare: