属性字典的速度比使用switch语句慢

本文关键字:switch 语句 字典 速度 属性 | 更新日期: 2023-09-27 18:28:04

我目前有一个类"ArisingViewModel",上面有大约20-30个属性,当我生成各种数据时,这些属性将被检查10000多次。

最初,我有一种方法从XML字符串中检索产生的属性值,如下所示:

    public object GetArisingPropertyValue(string propertyName)
    {
        switch (propertyName)
        {
            case "name_1":
                return Name1;
            case "another_name":
                return AnotherName;
            // etc.
        }
    }

但它被调整为使用属性字典,以便更容易更新,并使项目的其他部分的生活更轻松。所以我把我的财产字典设置成这样:

    private static readonly IDictionary<string, string> PropertyMap;

    static ArisingViewModel()
    {
        PropertyMap = new Dictionary<string, string>();
        var myType = typeof(ArisingViewModel);
        foreach (var propertyInfo in myType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
        {
            if (propertyInfo.GetGetMethod() != null)
            {
                var attr = propertyInfo.GetCustomAttribute<FieldNameAttribute>();
                if (attr == null)
                    continue;
                PropertyMap.Add(attr.FieldName, propertyInfo.Name);
            }
        }
    }

我将属性应用于任何相关属性,如:

    [FieldName("name_1")]
    public string Name1
    {
        get
        {
            return _arisingRecord.Name1;
        }
    }

然后使用以下方法查找属性名称/值:

    public static string GetPropertyMap(string groupingField)
    {
        string propName;
        PropertyMap.TryGetValue(groupingField, out propName);
        return propName; //will return null in case map not found.
    }
    public static object GetPropertyValue(object obj, string propertyName)
    {
        return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
    }

我的问题是,我发现使用旧的switch语句处理要快得多(使用一个非常简单的计时器类来测量系统花费的时间-约20秒vs约25秒)。

有人能建议我做错了什么吗,或者有什么方法可以改进当前的代码吗?

属性字典的速度比使用switch语句慢

我建议从StringTemplate 4的C#端口(BSD 3代码许可证)实现一个类似于ObjectModelAdaptor的类。此功能在模板渲染管道的性能关键部分中大量使用,并且评测表明当前实现的性能相当好。

该类使用了一种相当高效的缓存和调度机制,尽管可以通过使用ConcurrentDictionary和删除lock语句对.NET 4+用户进行改进。

您可能想要更改FindMember的实现,以实现具有属性的属性所特有的逻辑。