Skip to content

Instantly share code, notes, and snippets.

@bazzilic
Last active October 1, 2019 05:07
Show Gist options
  • Save bazzilic/8b0d8f753031b3fcb4ece17a3fcb89bd to your computer and use it in GitHub Desktop.
Save bazzilic/8b0d8f753031b3fcb4ece17a3fcb89bd to your computer and use it in GitHub Desktop.
byte[] vs IList<byte> performance comparison
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace ConsoleApp1
{
class Program {
static volatile byte res1, res2;
static void Main(string[] args) {
var sw = new Stopwatch();
var rnd = new Random();
var bytes = new byte[1024 * 1024 * 1024];
rnd.NextBytes(bytes);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
sw.Start();
res1 = TestArray(bytes);
sw.Stop();
var time1 = sw.ElapsedMilliseconds;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
sw.Restart();
res2 = TestIList(bytes);
sw.Stop();
var time2 = sw.ElapsedMilliseconds;
Console.WriteLine($"byte[] took: {time1} ms");
Console.WriteLine($"IList<byte> took: {time2} ms");
}
static byte TestArray(byte[] val) {
var res = val[0];
for (var i = 0; i < val.Length; i++)
res ^= val[i];
return res;
}
static byte TestIList(IList<byte> val) {
var res = val[0];
var len = val.Count;
for (var i = 0; i < len; i++)
res ^= val[i];
return res;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment