Skip to content

Instantly share code, notes, and snippets.

@JeffreyZhao
Created January 28, 2010 14:03
Show Gist options
  • Save JeffreyZhao/288765 to your computer and use it in GitHub Desktop.
Save JeffreyZhao/288765 to your computer and use it in GitHub Desktop.
namespace SimpleConsole
{
using System;
using System.Linq;
using System.Reflection.Emit;
using System.Reflection;
using System.Threading;
using System.Collections.Generic;
public class TypeBaseComparer : IComparer<TypeBase>
{
public int Compare(TypeBase x, TypeBase y)
{
return x.ID - y.ID;
}
}
public abstract class TypeBase
{
public int ID;
}
class Program
{
public static ModuleBuilder moduleBuilder = null;
static Program()
{
var assemblyName = new AssemblyName { Name = "SomeAssembly" };
var domain = Thread.GetDomain();
var asmBuilder = domain.DefineDynamicAssembly(
assemblyName, AssemblyBuilderAccess.Run);
moduleBuilder = asmBuilder.DefineDynamicModule("SomeModule");
}
static Type CreateType(int numberOfField)
{
var typeName = "TypeWith$" + numberOfField + "$Fields";
var typeBuilder = moduleBuilder.DefineType(
typeName, TypeAttributes.Class, typeof(TypeBase));
for (int i = 0; i < numberOfField; i++)
{
typeBuilder.DefineField("Field$" + i, typeof(int), FieldAttributes.Public);
}
return typeBuilder.CreateType();
}
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
CodeTimer.Initialize();
var random = new Random(DateTime.Now.Millisecond);
var array = Enumerable.Repeat(0, 1000 * 500).Select(_ => random.Next()).ToArray();
for (var num = 1; num <= 512; num *= 2)
{
var type = CreateType(num);
var arrayToSort = new TypeBase[array.Length];
for (var i = 0; i < array.Length; i++)
{
var instance = (TypeBase)Activator.CreateInstance(type);
instance.ID = array[i];
arrayToSort[i] = instance;
}
CodeTimer.Time(
String.Format("Type with {0} fields (Array.Sort)", num),
10, () => Sort(CloneArray(arrayToSort)));
CodeTimer.Time(
String.Format("Type with {0} fields (ArraySorter)", num),
10, () => ArraySorter(CloneArray(arrayToSort)));
}
Console.ReadLine();
}
static void Sort(TypeBase[] array)
{
Array.Sort(array, new TypeBaseComparer());
}
static void ArraySorter(TypeBase[] array)
{
new ArraySorter<TypeBase>().OrderBy(a => a.ID).Sort(array);
}
static T[] CloneArray<T>(T[] source)
{
var dest = new T[source.Length];
Array.Copy(source, dest, source.Length);
return dest;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment