Easy, Fast, Thread-safe Dictionary with a Type Key

From time to time I'll want to perform some operation on a subset of properties of a Type. However reflecting over types can be costly exercise. Since Types don't change at runtime the natural solution is to parse them once and cache the results. For small sets this works well. However  with hundreds of types, the performance starts to degrade. I've also noticed that the typeof operator is rather slow when compared to intrinsic is and as operators.

So to create a fast Type keyed dictionary I use the C# compiler and runtime JIT to do it for me. This solution is extremely fast and due to it's static nature, thread safe. But, it's also lazy-init because generic types aren't created until they're actually used at runtime.

´╗┐public static class TypeCache<T>
{
    public static readonly Type Type = typeof( T );
    public static readonly PropertyInfo[] Properties =
            typeof( T ).GetProperties();
}´╗┐

I can now get all the properties of a type like this:

foreach( var p in TypeCache<Entity>.Properties )
{
    Console.WriteLine( p.Name );
}

Since this is all actually part of the runtime types, the JIT and compiler can take advantage of any available optimizations. Analysis of the actual code JITted at at runtime shows the lookup TypeCache<Entity> actually indexes into a runtime table, whereas the typeof operator does an actual lookup by signature.

Limitations

  • It's ready only. It's a great lazily initialized structure but the factors that make it thread safe.
  • It's never garbage collected. Type information is always retained in the AppDomain so any statics created this way will always remain live.

Related Articles

Published : Jun 03, 2009
Views : 44801

Subscribe Subscribe | Blog Home

Downloads

Tags

  • code
  • development
  • tip