【问题标题】:GetMember vs GetField performance in C#C# 中的 GetMember 与 GetField 性能
【发布时间】:2012-03-23 10:54:33
【问题描述】:

任何人都知道最好使用什么来读取 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();
    }

选项 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;
    }

【问题讨论】:

  • 为什么不尝试 100,000 次,看看每种情况需要多长时间?
  • 哪个更快,它不太可能在任何程序中产生可衡量的差异。

标签: c# performance reflection


【解决方案1】:

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

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

您通常只读取一次属性,也许是几次。所以成本以昂贵的第一次为主,你使用的代码无关紧要。继续分析它。只要确保您不要将第一次的昂贵费用视为“实验错误”。

【讨论】:

    猜你喜欢
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多