gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:46:09 25 4
gpt4 key购买 nike

我目前有一个“ArisingViewModel”类,其中包含大约 20-30 个属性,当我生成各种数据时,这些属性将被检查 10,000 多次。

最初我有一种方法可以从 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 秒对~25 秒)处理速度要快得多。

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

最佳答案

我建议实现类似于 ObjectModelAdaptor 的类来自 StringTemplate 4 的 C# 端口(BSD 3 条款许可证)。此功能在模板渲染管道的性能关键部分大量使用,分析表明当前的实现性能相当好。

此类使用相当有效的缓存和分派(dispatch)机制,但可以通过使用 ConcurrentDictionary 为 .NET 4+ 用户改进它。并删除 lock声明。

您可能想要更改 FindMember 的实现使用属性实现特定于您的属性的逻辑。

关于c# - 属性字典的速度比使用 switch 语句慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26610966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com