From 0c92bf862811ce9b46b7f39f4fed7220b3a1cb95 Mon Sep 17 00:00:00 2001 From: Natan Vivo Date: Fri, 3 Feb 2017 12:46:28 -0200 Subject: [PATCH] Added caching to type->shortname and shortname->type conversions. --- Hyperion/Extensions/TypeEx.cs | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/Hyperion/Extensions/TypeEx.cs b/Hyperion/Extensions/TypeEx.cs index 4d787124..bff086d2 100644 --- a/Hyperion/Extensions/TypeEx.cs +++ b/Hyperion/Extensions/TypeEx.cs @@ -21,6 +21,9 @@ namespace Hyperion.Extensions { public static class TypeEx { + private static ConcurrentDictionary _shortNameToTypeCache = new ConcurrentDictionary(); + private static ConcurrentDictionary _typeToShortNameCache = new ConcurrentDictionary(); + //Why not inline typeof you ask? //Because it actually generates calls to get the type. //We prefetch all primitives here @@ -200,24 +203,27 @@ public static int GetTypeSize(this Type type) public static string GetShortAssemblyQualifiedName(this Type type) { - string fullName; - - if (type.IsGenericType) - { - var args = type.GetGenericArguments().Select(t => "[" + GetShortAssemblyQualifiedName(t) + "]"); - fullName = type.Namespace + "." + type.Name + "[" + String.Join(",", args) + "]"; - } - else + return _typeToShortNameCache.GetOrAdd(type, t => { - fullName = type.FullName; - } - - return fullName + ", " + type.Assembly.GetName().Name; + string fullName; + + if (t.IsGenericType) + { + var args = t.GetGenericArguments().Select(gt => "[" + GetShortAssemblyQualifiedName(gt) + "]"); + fullName = t.Namespace + "." + t.Name + "[" + String.Join(",", args) + "]"; + } + else + { + fullName = t.FullName; + } + + return fullName + ", " + t.Assembly.GetName().Name; + }); } public static Type GetTypeFromShortName(string shortName) { - return Type.GetType(shortName, ShortNameAssemblyResolver, null, true); + return _shortNameToTypeCache.GetOrAdd(shortName, name => Type.GetType(shortName, ShortNameAssemblyResolver, null, true)); } private static Assembly ShortNameAssemblyResolver(AssemblyName name)