using System;
using System.Collections;
using System.Reflection;
namespace ReflectionExample
{
public class ReflectionCache
{
// singleton
public static ReflectionCache Instance = new ReflectionCache();
private Hashtable list = new Hashtable();
private ReflectionCache()
{
}
// get methods for specified type
public MethodInfo[] GetMethods(Type type)
{
if(!list.ContainsKey(type))
{
// type was not found, so call reflection and store the result
// in the list for next time
list[type] = type.GetMethods();
}
// serve request from list
return (MethodInfo[])list[type];
}
}
}
using System;
using System.Collections;
using System.Reflection;
namespace ReflectionExample
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("ReflectionExample started...\n");
testUncached();
testCached();
Console.WriteLine("\npress any key to exit...");
Console.ReadLine();
}
private static int loops = 100000;
private static DateTime start;
private static DateTime stop;
private static TimeSpan diff;
private static Type[] testTypes = new Type[]
{ typeof(ArrayList), typeof(SortedList), typeof(Hashtable) };
private static void testUncached()
{
start = DateTime.Now;
for(int i=0; i<loops; i++)
{
testTypes[0].GetMethods();
testTypes[1].GetMethods();
testTypes[2].GetMethods();
}
stop = DateTime.Now;
diff = stop - start;
Console.WriteLine("uncached, elapsed time: " + diff.ToString());
}
private static void testCached()
{
start = DateTime.Now;
for(int i=0; i<loops; i++)
{
ReflectionCache.Instance.GetMethods(testTypes[0]);
ReflectionCache.Instance.GetMethods(testTypes[1]);
ReflectionCache.Instance.GetMethods(testTypes[2]);
}
stop = DateTime.Now;
diff = stop - start;
Console.WriteLine("cached, elapsed time: " + diff.ToString());
}
}
}
|