Skip to content

Instantly share code, notes, and snippets.

@kemokemo
Created July 6, 2024 14:33
Show Gist options
  • Save kemokemo/626586561363a59cdd5b23f6f6c80575 to your computer and use it in GitHub Desktop.
Save kemokemo/626586561363a59cdd5b23f6f6c80575 to your computer and use it in GitHub Desktop.
comparison of array and list with the dotnet 8
// original code is here: https://stackoverflow.com/a/454923
using System.Diagnostics;
Console.WriteLine("# Write once");
var elementCount = 6000000;
Random rand = new(12345);
var watch = Stopwatch.StartNew();
List<int> list = new(elementCount);
for (int i = 0; i < elementCount; i++)
{
list.Add(rand.Next(5000));
}
watch.Stop();
Console.WriteLine($"List : {watch.ElapsedMilliseconds} [ms]");
watch = Stopwatch.StartNew();
int[] array = new int[elementCount];
for (int i = 0; i < array.Length; i++)
{
array[i] = rand.Next(5000);
}
watch.Stop();
Console.WriteLine($"Array: {watch.ElapsedMilliseconds} [ms]");
Console.WriteLine("\n# Read 100 times");
Console.WriteLine("## for");
int chk = 0;
watch = Stopwatch.StartNew();
for (int rpt = 0; rpt < 100; rpt++)
{
int len = list.Count;
for (int i = 0; i < len; i++)
{
chk += list[i];
}
}
watch.Stop();
Console.WriteLine($"List : {watch.ElapsedMilliseconds} [ms]");
chk = 0;
watch = Stopwatch.StartNew();
for (int rpt = 0; rpt < 100; rpt++)
{
for (int i = 0; i < array.Length; i++)
{
chk += array[i];
}
}
watch.Stop();
Console.WriteLine($"Array: {watch.ElapsedMilliseconds} [ms]");
Console.WriteLine("\n## foreach");
chk = 0;
watch = Stopwatch.StartNew();
for (int rpt = 0; rpt < 100; rpt++)
{
foreach (int i in list)
{
chk += i;
}
}
watch.Stop();
Console.WriteLine($"List : {watch.ElapsedMilliseconds} [ms]");
chk = 0;
watch = Stopwatch.StartNew();
for (int rpt = 0; rpt < 100; rpt++)
{
foreach (int i in array)
{
chk += i;
}
}
watch.Stop();
Console.WriteLine($"Array: {watch.ElapsedMilliseconds} [ms]");
@kemokemo
Copy link
Author

kemokemo commented Jul 6, 2024

here is sample output:

# Write once
List : 64 [ms]
Array: 60 [ms]

# Read 100 times
## for
List : 2447 [ms]
Array: 1649 [ms]

## foreach
List : 2237 [ms]
Array: 1515 [ms]

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