Skip to content

Instantly share code, notes, and snippets.

@lunasorcery
Created August 13, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lunasorcery/a9798026c9c1b28d0772 to your computer and use it in GitHub Desktop.
Save lunasorcery/a9798026c9c1b28d0772 to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.Linq;
namespace LinqPerformance
{
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
int[] randomData = new int[10000000];
for (int i = 0; i < randomData.Length; ++i)
{
randomData[i] = rand.Next();
}
Stopwatch swFor = new Stopwatch();
swFor.Start();
int maxFor = MaxFor(randomData);
swFor.Stop();
Stopwatch swForeach = new Stopwatch();
swForeach.Start();
int maxForeach = MaxForeach(randomData);
swForeach.Stop();
Stopwatch swLinq = new Stopwatch();
swLinq.Start();
int maxLinq = MaxLinq(randomData);
swLinq.Stop();
Console.WriteLine("For loop {0:0.000}ms", 1000.0 * swFor.ElapsedTicks / Stopwatch.Frequency);
Console.WriteLine("Foreach loop {0:0.000}ms", 1000.0 * swForeach.ElapsedTicks / Stopwatch.Frequency);
Console.WriteLine("LINQ {0:0.000}ms", 1000.0 * swLinq.ElapsedTicks / Stopwatch.Frequency);
Console.ReadLine();
}
static int MaxFor(int[] randomData)
{
int max = int.MinValue;
for (int i = 0; i < randomData.Length; ++i)
{
if (randomData[i] > max)
{
max = randomData[i];
}
}
return max;
}
static int MaxForeach(int[] randomData)
{
int max = int.MinValue;
foreach (var val in randomData)
{
if (val > max)
{
max = val;
}
}
return max;
}
static int MaxLinq(int[] randomData)
{
return randomData.Max();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment