【发布时间】:2017-09-30 07:36:46
【问题描述】:
如何在保持公共接口的同时进一步提高以下代码的性能:
public interface IMapper<in TSource, in TDestination>
{
void Map(TSource source, TDestination destination);
}
public static TDestination Map<TSource, TDestination>(
this IMapper<TSource, TDestination> translator,
TSource source)
where TDestination : new()
{
var destination = new TDestination();
translator.Map(source, destination);
return destination;
}
public static List<TDestination> MapList<TSource, TDestination>(
this IMapper<TSource, TDestination> translator,
List<TSource> source)
where TDestination : new()
{
var destinationCollection = new List<TDestination>(source.Count);
foreach (var sourceItem in source)
{
var destinationItem = translator.Map(sourceItem);
destinationCollection.Add(destinationItem);
}
return destinationCollection;
}
示例用法
public class MapFrom { public string Property { get; set; } }
public class MapTo { public string Property { get; set; } }
public class Mapper : IMapper<MapFrom, MapTo>
{
public void Map(MapFrom source, MapTo destination)
{
destination.Property = source.Property;
}
}
var mapper = new Mapper();
var mapTo = mapper.Map(new MapFrom() { Property = "Foo" });
var mapToList = mapper.MapList(
new List<MapFrom>()
{
new MapFrom() { Property = "Foo" }
});
当前基准
当我针对原始手动转换运行基准测试时,我得到以下数字:
| Method | Job | Runtime | Mean | Error | StdDev | Min | Max | Scaled | ScaledSD | Gen 0 | Allocated |
|------------------- |----- |-------- |----------:|----------:|----------:|----------:|----------:|-------:|---------:|-------:|----------:|
| Baseline | Clr | Clr | 1.969 us | 0.0354 us | 0.0332 us | 1.927 us | 2.027 us | 1.00 | 0.00 | 2.0523 | 6.31 KB |
| Mapper | Clr | Clr | 9.016 us | 0.1753 us | 0.2019 us | 8.545 us | 9.419 us | 4.58 | 0.12 | 2.0447 | 6.31 KB |
| Baseline | Core | Core | 1.820 us | 0.0346 us | 0.0355 us | 1.777 us | 1.902 us | 1.00 | 0.00 | 2.0542 | 6.31 KB |
| Mapper | Core | Core | 9.043 us | 0.1725 us | 0.1613 us | 8.764 us | 9.294 us | 4.97 | 0.13 | 2.0447 | 6.31 KB |
这是基线的代码:
var mapTo = new MapTo() { Property = mapFrom.Property };
var mapToCollection = new List<MapTo>(this.mapFrom.Count);
foreach (var item in this.mapFrom)
{
destination.Add(new MapTo() { Property = item.Property });
}
基准代码
我在Dotnet-Boxed/Framework GitHub 存储库中有一个完整的项目,其中包含映射器和 Benchmark.NET 项目。
【问题讨论】:
-
我已经用我所做的基准测试中的详细信息更新了这个问题。我希望尽可能接近基线,甚至可能超过它。
-
为什么不实现 ISharedProperties 接口并使用 O(1) 赋值?
-
@shadow32
MapFrom和MapTo在我的示例中碰巧具有相同的属性名称,但情况并非总是如此。想想 Automapper。 -
“甚至可能超过它” - 是的,这不会发生,除非你的基线不是真正的基线。您的
MapList方法非常简单。如果你想拥有虚拟方法,你将不得不在虚拟调度上花费一些 CPU 时间。另外,是否有理由重新发明轮子?为什么不简单地使用 Automapper? AFAIK,Automapper 使用 Reflection.Emit 生成映射代码并编译它,以避免属性名称查找。 -
我发现的一个性能瓶颈是将
new T()用于受约束的类型参数。我发现传入Func<T>()会产生巨大的影响。如果您可以将您的代码编辑成minimal reproducible example,让我们真正轻松地运行测试,我可以看到它有多大的不同。 (但它仍然不会达到你的基线,当然......)
标签: c# .net performance allocation unchecked