C# C中的GetMember与GetField性能#
有人知道读取XmlEnumAttribute的最佳方法吗 选项1:使用GetMemberC# C中的GetMember与GetField性能#,c#,performance,reflection,C#,Performance,Reflection,有人知道读取XmlEnumAttribute的最佳方法吗 选项1:使用GetMember public static string XmlEnum(this Enum e) { Type type = e.GetType(); MemberInfo[] memInfo = type.GetMember(e.ToString()); if (memInfo != null && memInfo.Length >
public static string XmlEnum(this Enum e)
{
Type type = e.GetType();
MemberInfo[] memInfo = type.GetMember(e.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(XmlEnumAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((XmlEnumAttribute)attrs[0]).Name;
}
}
return e.ToString();
}
选项2:使用GetField
public static string XmlEnum2(this Enum e)
{
Type type = e.GetType();
FieldInfo info = type.GetField(e.ToString());
if (!info.IsDefined(typeof(XmlEnumAttribute), false))
{
return e.ToString();
}
object[] attrs = info.GetCustomAttributes(typeof(XmlEnumAttribute), false);
return ((XmlEnumAttribute)attrs[0]).Name;
}
为什么不试10万次,看看每种情况下需要多长时间 因为这不能测试属性的实际使用场景。第一次挖掘属性时它很昂贵,之后就很便宜了。费用是加载属性类的IL并对其进行编译,在程序集元数据中定位属性数据并从磁盘加载。然后调用属性构造函数并分配属性属性。读取属性的代码成本是微不足道的,相比之下,磁盘I/O的成本要高出几个数量级。第二次检索属性时,将完成大量工作,而且速度很快,只需从缓存的数据初始化对象即可
通常只读取一次属性,可能是几次。因此,成本主要取决于昂贵的第一次,您使用的代码无关紧要。继续,并概述它。只要确保你不会将昂贵的第一次视为“实验性错误”为什么不尝试100000次,看看每种情况下需要多长时间?无论哪种速度更快,都不可能在任何程序中产生可测量的差异。