Skip to content

Instantly share code, notes, and snippets.

@HaloFour
Created January 22, 2015 16:56
Show Gist options
  • Save HaloFour/a986f87949145c4c19d3 to your computer and use it in GitHub Desktop.
Save HaloFour/a986f87949145c4c19d3 to your computer and use it in GitHub Desktop.
Enumerable/Struct Perf Tests
using System;
using System.Collections.Generic;
using System.Diagnostics;
public struct CompilerGeneratedArgs3 : IEnumerable<int>
{
private struct Enumerator : IEnumerator<int>
{
private readonly CompilerGeneratedArgs3 args;
private int index;
public Enumerator(CompilerGeneratedArgs3 args) {
this.args = args;
index = -1;
}
public int Current
{
get
{
switch (index)
{
case 0:
return args.arg1;
case 1:
return args.arg2;
case 2:
return args.arg3;
default:
throw new InvalidOperationException();
}
}
}
public void Dispose() { }
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public bool MoveNext()
{
if (index < 2)
{
index += 1;
return true;
}
return false;
}
public void Reset()
{
index = -1;
}
}
private readonly int arg1, arg2, arg3;
public CompilerGeneratedArgs3(int arg1, int arg2, int arg3)
{
this.arg1 = arg1;
this.arg2 = arg2;
this.arg3 = arg3;
}
public IEnumerator<int> GetEnumerator()
{
return new Enumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
static class Program
{
private static int Test1(CompilerGeneratedArgs3 a)
{
int tally = 0;
foreach (int i in a)
{
tally += i;
}
return tally;
}
private static int Test2<TParams>(TParams a) where TParams : struct, IEnumerable<int>
{
int tally = 0;
foreach (int i in a)
{
tally += i;
}
return tally;
}
private static int Test3(IEnumerable<int> a)
{
int tally = 0;
foreach (int i in a)
{
tally += i;
}
return tally;
}
static void Main()
{
const int COUNT = 100000000;
CompilerGeneratedArgs3 a1 = new CompilerGeneratedArgs3(1, 2, 3);
Test1(a1);
Test2(a1);
Test3(a1);
Stopwatch watch = new Stopwatch();
try
{
var process = Process.GetCurrentProcess();
process.ProcessorAffinity = new IntPtr(1);
process.PriorityClass = ProcessPriorityClass.RealTime;
watch.Restart();
for (int i = 0; i < COUNT; i++)
{
Test1(new CompilerGeneratedArgs3(1, 2, 3));
}
watch.Stop();
Console.WriteLine("Test1: {0}", watch.Elapsed);
watch.Restart();
for (int i = 0; i < COUNT; i++)
{
Test2(new CompilerGeneratedArgs3(1, 2, 3));
}
watch.Stop();
Console.WriteLine("Test2: {0}", watch.Elapsed);
watch.Restart();
for (int i = 0; i < COUNT; i++)
{
Test3(new CompilerGeneratedArgs3(1, 2, 3));
}
watch.Stop();
Console.WriteLine("Test3: {0}", watch.Elapsed);
watch.Restart();
for (int i = 0; i < COUNT; i++)
{
Test3(new int[] { 1, 2, 3 });
}
watch.Stop();
Console.WriteLine("Test3/Array: {0}", watch.Elapsed);
}
catch (Exception exception)
{
Console.Error.WriteLine(exception.ToString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment