Perfomance of Mapping C# Poco objects 1
02/16/2018
2 minutes
In the series of the following posts, I will explore a couple of ways to map one object to another object, and will measure the performance of these methods.
The task will be map 2 types to each other:
public class People1 { public int Age { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public Guid Id { get; set; } public double Weight { get; set; } public double Height { get; set; } public string NationalId { get; set; } public God1 God { get; set; } } public class People2 { public int Age { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public Guid Id { get; set; } public double Weight { get; set; } public double Height { get; set; } public string NationalId { get; set; } public God2 God { get; set; } } public class God1 { public string Name { get; set; } } public class God2 { public string Name { get; set; } }
Measurement
We will map each property in type People1 to People2 and the same for God1 to God2. There will be 3 different approaches I try in these series.
In the tests, I instanciate a People1 typed object, I configure a mapper under test, and start a stopwatch. The measurement will run the mapper function a million times. Finally, we stop the stopwatch and print the results to the console. I repeat the measurements 7 times, eliminate the best and worst executions times, and calculate an average time. We run the tests in Release build optimized, "trying" to avoiding GC to kick in while running the tests by GC.KeepAlive and appropiate GC latency mode.
AutoMapper
At first I will use a library called AutoMapper. With this, I create a profile, which maps each People and God types respectively, I register this profile, and create a mapper. This mapper is then used later to do the actual mapping work.
MapperConfiguration config = new MapperConfiguration(c => { c.AddProfile(new DataProfile()); }); var mapper = config.CreateMapper(); ... target = mapper.Map(source); //Doing the mapping
Running this on my machine (in Release mode, using .net core), it takes an average of 273.8 ms to run the mappings.
The following post will explore mapping objects by hand, to see a comparison.