.NET获取枚举DescriptionAttribute描述信息性能改进的多种方法

2019-05-22 21:25:11刘景俊

  来测试一下,看看效果吧!

[Test]
public void GetDescriptionByDictionaryWithException_Test()
{
var enums = this.GetTestEnums();
Console.WriteLine(enums.Count);
TestHelper.InvokeAndWriteAll(() =>
{
System.Threading.Tasks.Parallel.For(0, 1000000, (i, obj) =>
{
foreach (var item in enums)
{
var a = item.GetDescriptionByDictionaryWithException();
}
});
});
}
//测试结果:
80
TimeSpan:1,208.0000ms
MemoryUsed:230.9453KB
CollectionCount(0):1.00

  测试结果来看,基本上差不多,在时间上略微快乐一点点,1,208.0000ms:1,860.0000ms,执行8000w次快600毫秒,好像差别也不大啊,这是为什么呢?

  这个其实就是Dictionary的问题了,Dictionary内部使用散列算法计算存储地址,其查找的时间复杂度为o(1),他的查找效果是非常快的,而本方法中利用了异常处理,异常捕获本身是有一定性能影响的。

2.3 推荐简单方案:ConcurrentDictionary

  ConcurrentDictionary是一个线程安全的字典类,代码:

private static ConcurrentDictionary<Enum, string> _ConcurrentDictionary = new ConcurrentDictionary<Enum, string>();
public static string GetDescriptionByConcurrentDictionary(this Enum @this)
{
return _ConcurrentDictionary.GetOrAdd(@this, (key) =>
{
var type = key.GetType();
var field = type.GetField(key.ToString());
return field == null ? key.ToString() : GetDescription(field);
});
}

  测试代码及测试结果:

[Test]
public void GetDescriptionByConcurrentDictionary_Test()
{
var enums = this.GetTestEnums();
Console.WriteLine(enums.Count);
TestHelper.InvokeAndWriteAll(() =>
{
System.Threading.Tasks.Parallel.For(0, 1000000, (i, obj) =>
{
foreach (var item in enums)
{
var a = item.GetDescriptionByConcurrentDictionary();
}
});
});
}
//测试结果:
80
TimeSpan:1,303.0000ms
MemoryUsed:198.0859KB
CollectionCount(0):1.00 

2.4 正式的代码

  综上所述,解决了性能问题、位域枚举问题的正式的代码:

/// <summary>
/// 获取枚举的描述信息(Descripion)。
/// 支持位域,如果是位域组合值,多个按分隔符组合。
/// </summary>
public static string GetDescription(this Enum @this)
{
return _ConcurrentDictionary.GetOrAdd(@this, (key) =>
{
var type = key.GetType();
var field = type.GetField(key.ToString());
//如果field为null则应该是组合位域值,
return field == null ? key.GetDescriptions() : GetDescription(field);
});
}
/// <summary>
/// 获取位域枚举的描述,多个按分隔符组合
/// </summary>
public static string GetDescriptions(this Enum @this, string separator = ",")
{
var names = @this.ToString().Split(',');
string[] res = new string[names.Length];
var type = @this.GetType();
for (int i = 0; i < names.Length; i++)
{
var field = type.GetField(names[i].Trim());
if (field == null) continue;
res[i] = GetDescription(field);
}
return string.Join(separator, res);
}
private static string GetDescription(FieldInfo field)
{
var att = System.Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false);
return att == null ? field.Name : ((DescriptionAttribute)att).Description;
}