Created
July 6, 2024 14:33
-
-
Save kemokemo/626586561363a59cdd5b23f6f6c80575 to your computer and use it in GitHub Desktop.
comparison of array and list with the dotnet 8
This file contains hidden or 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
// 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]"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
here is sample output: