Skip to content

Instantly share code, notes, and snippets.

@jeffputz
Last active January 2, 2022 20:02
Show Gist options
  • Save jeffputz/09430a2f88500118f75fbf7f6a6b411d to your computer and use it in GitHub Desktop.
Save jeffputz/09430a2f88500118f75fbf7f6a6b411d to your computer and use it in GitHub Desktop.
Array traversal: for vs. LINQ
using System;
using System.Diagnostics;
int[,] a = {
{1,2,3,4,5,6,7,8},
{4,5,6,7,8,9,10,1},
{7,8,9,10,11,12,13,14},
{10,1,2,3,4,5,6,7},
{1,2,3,4,5,6,7,8},
{4,5,6,7,8,9,10,1},
{7,8,9,10,11,12,13,14},
{10,1,2,3,4,5,6,7},
{1,2,3,4,5,6,7,8},
{4,5,6,7,8,9,10,1},
{7,8,9,10,11,12,13,14},
{10,1,2,3,4,5,6,7},
{1,2,3,4,5,6,7,8},
{4,5,6,7,8,9,10,1},
{7,8,9,10,11,12,13,14},
{10,1,2,3,4,5,6,7}
};
var sw = new Stopwatch();
sw.Start();
var count = 0;
for (int i = 0; i < a.GetLength(0); i++)
{
for (int j = 0; j < a.GetLength(1); j++)
if (a[i,j] == 1)
count++;
}
Console.WriteLine(count);
sw.Stop();
Console.WriteLine($"for loops: {sw.ElapsedMilliseconds}ms");
sw = new Stopwatch();
sw.Start();
var xRange = Enumerable.Range(0, a.GetLength(0));
var yRange = Enumerable.Range(0, a.GetLength(1));
var result = xRange.SelectMany(x => yRange.Select(y => a[x, y]));
var count2 = result.Count(x => x == 1);
Console.WriteLine(count2);
sw.Stop();
Console.WriteLine($"LINQ: {sw.ElapsedMilliseconds}ms");
var list = new List<List<int>> {
new() {1,2,3,4,5,6,7,8},
new() {4,5,6,7,8,9,10,1},
new() {7,8,9,10,11,12,13,14},
new() {10,1,2,3,4,5,6,7},
new() {1,2,3,4,5,6,7,8},
new() {4,5,6,7,8,9,10,1},
new() {7,8,9,10,11,12,13,14},
new() {10,1,2,3,4,5,6,7},
new() {1,2,3,4,5,6,7,8},
new() {4,5,6,7,8,9,10,1},
new() {7,8,9,10,11,12,13,14},
new() {10,1,2,3,4,5,6,7},
new() {1,2,3,4,5,6,7,8},
new() {4,5,6,7,8,9,10,1},
new() {7,8,9,10,11,12,13,14},
new() {10,1,2,3,4,5,6,7}
};
sw = new Stopwatch();
sw.Start();
var count3 = list.Select(x => x.Count(y => y == 1)).Sum();
Console.WriteLine(count3);
sw.Stop();
Console.WriteLine($"List<List<int>> LINQ: {sw.ElapsedMilliseconds}ms");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment