c# - 我使用反射的自定义映射可以更快吗?

标签 c# caching reflection orm mapping

我有以下方法将源对象映射到重复的目标对象。然而,只有标有特定属性的某些属性需要映射到新对象。

我的映射器当前如下所示:

public static class BaseObjectExtensions
{
    private static readonly Dictionary<string, Attribute[]> AttributeCache = new Dictionary<string, Attribute[]>();
    private static readonly Dictionary<string, PropertyInfo[]> PropertyCache = new Dictionary<string, PropertyInfo[]>();

    public static void Map(this IBaseObject destination, IBaseObject source)
    {
        if (source == null)
        {
            return;
        }

        var t = source.GetType();
        PropertyInfo[] properties;
        lock (PropertyCache)
        {
            if (!PropertyCache.TryGetValue(t.FullName, out properties))
            {
                properties = t.GetProperties();
                PropertyCache.Add(t.FullName, properties);
            }
        }

        lock (AttributeCache)
        {
            foreach (PropertyInfo prop in properties)
            {
                Attribute[] attrs;
                string k = t.FullName + prop;
                if (!AttributeCache.TryGetValue(k, out attrs))
                {
                    attrs = Attribute.GetCustomAttributes(prop);
                    AttributeCache.Add(k, attrs);
                }

                if (attrs.OfType<DatabaseMap>().Any())
                {
                    prop.SetValue(destination, prop.GetValue(source));
                }
            }
        }
    }
}

此 map 可用于单个项目或项目集合。我注意到性能瓶颈,因此经过大量研究后我添加了两个缓存。大量元素集合的时间如下:

  • 没有反射缓存:26.6 秒
  • 使用反射缓存(ConcurrentDictionary):31 秒
  • 使用反射缓存(锁定):4 秒

加速是显着的,但我认为它仍然可以更好。经过大量阅读后,我发现了类似 FastInvoke 的东西和 another FastInvoke但似乎无法将它们应用到我想要完成的事情上。

我还能做些什么来加快速度吗?

最佳答案

我认为为了获得最佳性能,您应该使用 Reflection.Emit 编译映射器,或使用现有的之一: Emit mapper vs valueinjecter or automapper performance

关于c# - 我使用反射的自定义映射可以更快吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20019150/

相关文章:

caching - 告诉浏览器不要缓存的正确方法是什么?

c# - 我正在使用反射来获取 ASP.NET 中的属性名称和值需要一些优化建议

java - 安卓| DexClassLoader,ClassNotFound 异常

c++ - 如何实例化其构造函数需要来自包含类名的字符串的参数的对象?

c# - 反射.Assembly.CreateInstance(字符串)

c# - Azure:如何创建对内部端点的服务引用

java - 条件延迟处理

C++缓存性能奇怪的行为

c# - .NET:解析本地化货币

c# - 根据 bindingcontext 删除 ListView item