我有以下方法将源对象映射到重复的目标对象。然而,只有标有特定属性的某些属性需要映射到新对象。
我的映射器当前如下所示:
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/