如何提高 C# 对象映射代码的性能

Muh*_*eed 5 .net c# performance allocation unchecked

如何在保持公共接口的同时进一步提高以下代码的性能:

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;
}
Run Code Online (Sandbox Code Playgroud)

示例用法

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" } 
    });
Run Code Online (Sandbox Code Playgroud)

当前基准

当我针对原始手动转换运行基准测试时,这些是我得到的数字:

|             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 |
Run Code Online (Sandbox Code Playgroud)

这是基线的代码:

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 });
}
Run Code Online (Sandbox Code Playgroud)

基准代码

我有一个完整的工作项目,其中包含Dotnet-Boxed/Framework GitHub 存储库中的映射器和 Benchmark.NET 项目。

Kir*_*kiy 5

在实施评论中讨论的建议后,这是MapList<TSource, TDestination>我能够提出的最有效的实施方案:

using System;
using System.Collections.Generic;
using System.Linq.Expressions;

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)
    {
        TDestination dest = Factory<TDestination>.Instance();
        translator.Map(sourceItem, dest);
        destinationCollection.Add(dest);
    }

    return destinationCollection;
}

static class Factory<T>
{
    // Cached "return new T()" delegate.
    internal static readonly Func<T> Instance = CreateFactory();

    private static Func<T> CreateFactory()
    {
        NewExpression newExpr = Expression.New(typeof(T));

        return Expression
            .Lambda<Func<T>>(newExpr)
            .Compile();
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,我设法利用了 Jon Skeet 的建议,在不需要调用者提供委托的情况下不要使用,从而保留了您的 API。new TDestination()Func<TDestination>

当然,编译工厂委托的成本是不可忽略的,但在常见的映射场景中,我预计它是值得的。