Perfomance of Mapping C# Poco objects 2
03/10/2018
2 minutes
In the series of these posts, I explore a couple of ways to map one object to another object, and will measure the performance of that. In the first part, I used AutoMapper. In this part I will use the poor man's solution by writing the mapping by hand. This has a couple of disadvantages, hence libraries like AutoMapper exists. But if someone is willing to sacrifice writing some extra lines of code, he can ditch a dependency to a library. In the previous post I mapped People and God objects, one to another. Let's see the same doing by hand:
public static People2 Map(this People1 source, People2 target) { target.Age = source.Age; target.FirstName = source.FirstName; target.LastName = source.LastName; target.Height = source.Height; target.Weight = source.Weight; target.Id = source.Id; target.NationalId = source.NationalId; target.God = source.God?.Map(target.God); return target; } public static God2 Map(this God1 source, God2 target) { target.Name = source.Name; return target; }
The given solution uses extension methods. This is a good practice when we do not have the source or chance to modify the source or target objects (say because they are in a 3rd party library). Still extension methods give a convenient way using this method on an existing People1 typed object. One interesting part here is that this extension method expects the target object to be existing at the point of invocation, while when using AutoMapper we relied on the library to create the target objects. This is an important observation when measuring the performance, thus we have to include the object instansiaton as well:
target = source.Map(new People2() { God = new God2() });
Running the above code in the same environment as described by the previous post we it takes 39ms an average. That is a 7 times faster. But it has a major downside. We have to build an extension method for every type, which can be a huge amount of work. So is there a better, more generalized option? The third part of this series will explore this question.