perf: EnumUtils micro-optimization, potential thread safety improvements

This commit is contained in:
Chris Cameron
2018-07-20 11:28:16 -04:00
parent 0c462ad614
commit 6fb1e53776

View File

@@ -126,10 +126,14 @@ namespace ICD.Common.Utils
throw new ArgumentNullException("type"); throw new ArgumentNullException("type");
// Reflection is slow and this method is called a lot, so we cache the results. // Reflection is slow and this method is called a lot, so we cache the results.
if (!s_EnumValuesCache.ContainsKey(type)) object[] cache;
s_EnumValuesCache[type] = GetValuesUncached(type).ToArray(); if (!s_EnumValuesCache.TryGetValue(type, out cache))
{
cache = GetValuesUncached(type).ToArray();
s_EnumValuesCache[type] = cache;
}
return s_EnumValuesCache[type]; return cache;
} }
/// <summary> /// <summary>
@@ -280,13 +284,23 @@ namespace ICD.Common.Utils
Type type = typeof(T); Type type = typeof(T);
if (!s_EnumFlagsCache.ContainsKey(type)) Dictionary<object, object[]> cache;
s_EnumFlagsCache.Add(type, new Dictionary<object, object[]>()); if (!s_EnumFlagsCache.TryGetValue(type, out cache))
{
cache = new Dictionary<object, object[]>();
s_EnumFlagsCache[type] = cache;
}
if (!s_EnumFlagsCache[type].ContainsKey(value)) object[] flags;
s_EnumFlagsCache[type][value] = GetValues<T>().Where(e => HasFlag(value, e)).Cast<object>().ToArray(); if (!cache.TryGetValue(value, out flags))
{
flags = GetValues<T>().Where(e => HasFlag(value, e))
.Cast<object>()
.ToArray();
cache[value] = flags;
}
return s_EnumFlagsCache[type][value].Cast<T>(); return flags.Cast<T>();
} }
/// <summary> /// <summary>