A simple benchmark using BenchmarkDotNet for the different techniques of mapping database data to objects.
- Json Serialize-Deserialize - Uses Newtonsoft.Json library to serialize a dictionary of property names and its value then deserialzing it to an object.
- Reflection - Hand made plain old reflection.
- FastMember Reflection - Uses Marc Gravell's FastMember Library that improves reflection performance.
- Optimized Reflection - Inspired by Google ProtoBuf which caches object setter to drastically improve mapping performance.
As()
- Maps a single row to an object.AsArray()
- Maps all the rown to a list of objects.
The methods of each mapping technique are run on 10, 100, 10000 rows.
public class Model
{
public Guid Id { get; set; } // Mock = Guid.NewGuid()
public int Integer { get; set; } // Mock = int.MaxValue
public decimal Decimal { get; set; } // Mock = decimal.MaxValue
public string String { get; set; } // Mock = null
public DateTime Date { get; set; } // Mock = DateTime.UtcNow
}
- In mapping single rows, all techniques are very close to each other. Json Serialize-Deserialize happens to have the fastest time but it is frankly small, in 100ths of a microsecond which barely affects performance in practice.
- In mapping multiple rows the performance competition can be narrowed down to two (2) techniques, Json Serialize-Deserialize and Optimized Reflection. Plain old reflection and FastMember are 4x slower than the latter.
- At 10 rows Json Serialize-Deserialize is faster than Optimized Reflection by ~8 %. As the magnitude of rows increase by 10 (100, 10000), Optimized Reflection seems to be faster at ~3 %.
- At single row mapping all techniques pratically performs the same.
- At multiple row mapping either Json Serialize-Deserialize or Optimized Reflection are good options. The choice will just depend on usage and overhead since Newtonsoft.Json is a whole library compared to reflection which is built in.
Yeet a Pull Request