GetMember与C#中的GetField性能

fra*_*t79 0 c# reflection performance

任何人都知道最好用什么来读取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 > 0)
        {
            object[] attrs = memInfo[0].GetCustomAttributes(typeof(XmlEnumAttribute), false);
            if (attrs != null && attrs.Length > 0)
            {
                return ((XmlEnumAttribute)attrs[0]).Name;
            }
        }
        return e.ToString();
    }
Run Code Online (Sandbox Code Playgroud)

选项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;
    }
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 7

为什么不尝试100,000次,看看每种情况需要多长时间?

因为这不会测试属性的实际使用方案.在你一次挖掘属性时它很昂贵,之后很便宜.费用是为属性类加载IL并对其进行编译,将属性数据定位在程序集元数据中并从磁盘加载它.然后调用属性构造函数并分配属性属性.您的代码读取属性的成本是花生与此相比,它是昂贵的磁盘I/O几个数量级.第二次检索属性时,很多工作都已完成,而且速度很快,只是从缓存的数据初始化对象.

您通常只读取一次属性,可能只读取一次.所以成本主要是昂贵的第一次,你使用的代码很少.来吧,剖析它.只要确保你不把那个昂贵的第一次当作"实验性错误".