Created
June 9, 2020 11:23
-
-
Save aevitas/2e47d13e70870ecca27294c1b6eeb9de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MappingProfile : Profile | |
{ | |
public MappingProfile() | |
{ | |
CreateMap<Entity, Model>(); | |
} | |
} | |
public class MappingBenchmarks | |
{ | |
private static readonly IMapper Mapper = new Mapper(new MapperConfiguration(expression => | |
{ | |
expression.AddProfile<MappingProfile>(); | |
})); | |
private static readonly List<Entity> Entities = Enumerable.Range(0, 10000).Select(i => GenerateRandomEntity()).ToList(); | |
[Benchmark] | |
public void AutoMapper() | |
{ | |
var models = Mapper.Map<List<Model>>(Entities); | |
} | |
[Benchmark] | |
public void ManualMapping() | |
{ | |
var models = Entities.Select(ToModel); | |
} | |
private static Model ToModel(Entity entity) | |
{ | |
return new Model | |
{ | |
A = entity.A, | |
B = entity.B, | |
C = entity.C, | |
Id = entity.Id | |
}; | |
} | |
private static Entity GenerateRandomEntity() | |
{ | |
var random = new Random(); | |
return new Entity | |
{ | |
A = GenerateRandomString(32), | |
B = GenerateRandomString(24), | |
C = (decimal)random.NextDouble() * 10000, | |
Id = random.Next(0, 100000) | |
}; | |
} | |
private static string GenerateRandomString(int length) | |
{ | |
char[] chars = "abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray(); | |
var random = new Random(); | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i < length - 1; i++) | |
sb.Append(chars[random.Next(0, chars.Length)]); | |
return sb.ToString(); | |
} | |
} | |
internal class Program | |
{ | |
private static async Task Main(string[] args) | |
{ | |
BenchmarkRunner.Run<MappingBenchmarks>(); | |
Console.ReadLine(); | |
} | |
} | |
public class Entity | |
{ | |
public int Id { get; set; } | |
public string A { get; set; } | |
public string B { get; set; } | |
public decimal C { get; set; } | |
} | |
public class Model | |
{ | |
public int Id { get; set; } | |
public string A { get; set; } | |
public string B { get; set; } | |
public decimal C { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment