Caching type extension methods

This commit is contained in:
Chris Cameron
2018-03-26 16:00:27 -04:00
parent c21b8d08da
commit 487a2fc006

View File

@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using ICD.Common.Utils.Collections; using ICD.Common.Utils.Collections;
#if SIMPLSHARP #if SIMPLSHARP
using Crestron.SimplSharp.Reflection; using Crestron.SimplSharp.Reflection;
@@ -44,6 +45,18 @@ namespace ICD.Common.Utils.Extensions
typeof(float), typeof(float),
}; };
private static readonly Dictionary<Type, Type[]> s_TypeAllTypes;
private static readonly Dictionary<Type, Type[]> s_TypeBaseTypes;
/// <summary>
/// Static constructor.
/// </summary>
static TypeExtensions()
{
s_TypeAllTypes = new Dictionary<Type, Type[]>();
s_TypeBaseTypes = new Dictionary<Type, Type[]>();
}
/// <summary> /// <summary>
/// Returns true if the given type is a numeric type. /// Returns true if the given type is a numeric type.
/// </summary> /// </summary>
@@ -118,13 +131,18 @@ namespace ICD.Common.Utils.Extensions
if (extends == null) if (extends == null)
throw new ArgumentNullException("extends"); throw new ArgumentNullException("extends");
yield return extends; if (!s_TypeAllTypes.ContainsKey(extends))
{
Type[] types =
extends.GetBaseTypes()
.Concat(extends.GetInterfaces())
.Prepend(extends)
.ToArray();
foreach (Type type in extends.GetBaseTypes()) s_TypeAllTypes.Add(extends, types);
yield return type; }
foreach (Type type in extends.GetInterfaces()) return s_TypeAllTypes[extends];
yield return type;
} }
/// <summary> /// <summary>
@@ -137,17 +155,31 @@ namespace ICD.Common.Utils.Extensions
if (extends == null) if (extends == null)
throw new ArgumentNullException("extends"); throw new ArgumentNullException("extends");
if (!s_TypeBaseTypes.ContainsKey(extends))
{
Type[] types = GetBaseTypesInternal(extends).ToArray();
s_TypeBaseTypes.Add(extends, types);
}
return s_TypeBaseTypes[extends];
}
private static IEnumerable<Type> GetBaseTypesInternal(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
do do
{ {
extends = extends type = type
#if !SIMPLSHARP #if !SIMPLSHARP
.GetTypeInfo() .GetTypeInfo()
#endif #endif
.BaseType; .BaseType;
if (extends != null) if (type != null)
yield return extends; yield return type;
} while (extends != null); } while (type != null);
} }
} }
} }