How to map efficiently objects in .NET

What to do when we have 2 similar data structures and we need to build one structure based on another? How to do it better and more efficiently? The first idea is to rewrite all properties manually one by one. This solution is usually the most efficient. It is also the most flexible. The disadvantage is the workload needed for implementation, and any change in the definition of data structures requires changes in the mapping code. That's why there are a lot of auto mapping solutions. Automapper simplifies the mapping code to one line. This solution can automatically map properties with the same or similar names. It also allows you to manually define the mapping of certain fragments. Automapper is definitely worth where the structures are identical or almost identical, whereas if the structures have different - often instead of writing the automaper configuration code, it is much easier to write your own mapper. In test I compared the performance of custom mapper and two free libraries available as packages in nuget - Automapper 7.0.1 and Moon.FastAutomapper 1.1.2.
All tests works on table with 100 000 structured items.
Source code for:Performance tests
Source code for: Moon.FastAutomapper
Source code for:Automapper

 Automapper 7.0.1

7751ms 

 Moon.FastAutomapper 1.1.2

67ms 

 Custom automapper with for loop

45ms 

 Custom automapper with linq

69ms 



Conclusions:

Moon.FastAutomapper is faster about 70 times then Automapper, and performance of FastAutomapper is similar for custom mapper. It is possible because FastAutoMapper uses a generated on the fly and cached mapping code. The library has 100% coverage in unit tests, so although it is new, it looks quite solid.

Komentarze