Skip to content

Instantly share code, notes, and snippets.

@fraguada
Last active July 26, 2021 11:15
Show Gist options
  • Save fraguada/301fe31b939e6889514969cb1bbec37c to your computer and use it in GitHub Desktop.
Save fraguada/301fe31b939e6889514969cb1bbec37c to your computer and use it in GitHub Desktop.
c# Array copying performance test
// 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);
}
@fraguada
Copy link
Author

fraguada commented Aug 9, 2018

Typical results on W10 VMWare:

  • Array.Copy: 360ms
  • Linq: 31335ms
  • Buffer.BlockCopy: 84ms
  • ArraySegment: 600ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment