AutoMapper is an object-object mapper. Object-object mapping works by transforming an input object of one type into an output object of a different type. It has a large amount of settings which sometimes are really hard to setup. In my projects, I needed to auto-map simple objects which don’t have collection properties, only a big tree of custom property types- TestCase object which has a property of type TestStep and so on. Also, there are rare cases in which the AutoMapper is not working. So, I created ReducedAutoMapper, which is only 150 lines of code but it runs 180% faster that AutoMapper.

Reduced AutoMapper Explained

The main goal of the object-object mappers is to map object A to object B.

Original Object Type- Not Serializable

Destination Object- Serializable (identical properties, only serialization attributes added)

The first step in the object-object mapper is to register the relations between the Original and Destination objects.

In order to accomplish the task, the class contains mappingTypes Dictionary which stores the relations between the original and destination types. Through the generic method CreateMap, the types are added to the dictionary.

Sample Registration

How the main AutoMapping Algorithm Works?

In its core, the ReducedAutoMapper heavily uses Reflection to get the information related to the auto-mapped objects.

First it gets the properties of the source object.

Next it iterates through them. If a property with the same name it is not present in the destination object, it is skipped. If there is and it is not our custom class (it is a System class like- string, int, DateTime), its value is set to the original’s property one.

If the type of the property is a custom type and it is not present in the dictionary, it is not auto-mapped.

Otherwise in order the new value of the destination object to be calculated, we use reflection to call recursively the generic Map method.

There is an optimization if the values of the inner property types are already calculated. When a registered destination type is calculated, its value is placed in the alreadyInitializedObjects collection and the method Map is not called recursively afterwards.

If you need to auto-map collection of objects you can use the third method of the ReducedAutoMapper class- MapList.

Compare AutoMapper with ReducedAutoMapper

I created a simple console application where I initialized a really large objects with more than 1000 properties. The number of the created objects is 100000.

Above you can find the first source class- FirstObject. Below you can find the other two.

SecondObject

ThirdObject

The code below tests the ReducedAutoMapper with 100000 objects.

Results



The code below tests the AutoMapper with 100000 objects.

Results



As you can see from the results above, the ReducedAutoMapper performed >180% better than AutoMapper.

