AutoMapper: What is the difference between MapFrom and ResolveUsing?

后端 未结 5 1899
执笔经年
执笔经年 2020-11-30 07:00

Ignoring the ResolveUsing overloads that take an IValueResolver, and looking only at these 2 methods:

v         


        
5条回答
  •  没有蜡笔的小新
    2020-11-30 07:51

    I just did some benchmarks using the new C# 6 null conditional operator ?.

    Consider the following scenario: class A has a child class B, which has a child C, whose Name property we want to flatten into a DTO. I tested two variants:

    // using mapfrom
    CreateMap()
        .ForMember(dto => dto.Name, o => o.MapFrom(a => a.B.C.Name));
    
    // using resolveusing with elvis
    CreateMap()
        .ForMember(dto => dto.Name, o => o.ResolveUsing(x => x.Y?.Z?.Name));
    

    I called _mapper.Map(x); or _mapper.Map(a); for 1000 different ResolveUsingX x and MapFromA a and took the time using a System.Diagnostics.StopWatch. Here are my results:

    Distinct elements per batch: 1000; # batches for average: 25
    
    A->B->C.Name, C is never null.
    MapForm - average time taken for 1000x: 5527,84 ticks = 1,44 ms.
    ResolveUsing - average time taken for 1000x: 5479,76 ticks =  1,4 ms.
    
    A->B->C.Name, C is null 1/3 of the time.
    MapForm - average time taken for 1000x: 72924,4 ticks = 27,44 ms.
    ResolveUsing - average time taken for 1000x: 5351,2 ticks =  1,48 ms.
    
    A->B->C.Name, C is null 1/2 of the time.
    MapForm - average time taken for 1000x: 107016,92 ticks = 40,52 ms.
    ResolveUsing - average time taken for 1000x: 5835,32 ticks =  1,56 ms.
    
    A->B->C.Name, C is null 2/3 of the time.
    MapForm - average time taken for 1000x: 141437,96 ticks = 53,64 ms.
    ResolveUsing - average time taken for 1000x: 5789,72 ticks =  1,56 ms.
    

    MapFrom has to catch NullReferenceExceptions, which is slower than ResolveUsing with the elvis operator ?.

提交回复
热议问题