If some one knows any more ways of doing this in .NET and also what is your opinions about that approaches? Which approach you choose and why?
Here is the tests of different ways of object copy in .NET.
Tests Related to this original thread: How to copy value from class X to class Y with the same property name in c#?
So, here it is, you can run it yourself:
static void Main(string[] args)
{
Student _student = new Student();
_student.Id = 1;
_student.Name = "Timmmmmmmmaaaahhhh";
_student.Courses = new List<int>();
_student.Courses.Add(101);
_student.Courses.Add(121);
Stopwatch sw = new Stopwatch();
Mapper.CreateMap<Student, StudentDTO>();
StartTest(sw, "Auto Mapper");
for (int i = 0; i < 1000000; i++)
{
StudentDTO dto = Mapper.Map<Student, StudentDTO>(_student);
}
StopTest(sw);
StartTest(sw, "Implicit Operator");
for (int i = 0; i < 1000000; i++)
{
StudentDTO itemT = _student;
}
StopTest(sw);
StartTest(sw, "Property Copy");
for (int i = 0; i < 1000000; i++)
{
StudentDTO itemT = new StudentDTO
{
Id = _student.Id,
Name = _student.Name,
};
itemT.Courses = new List<int>();
foreach (var course in _student.Courses)
{
itemT.Courses.Add(course);
}
}
StopTest(sw);
StartTest(sw, "Emit Mapper");
ObjectsMapper<Student, StudentDTO> emitMapper = ObjectMapperManager.DefaultInstance.GetMapper<Student, StudentDTO>();
for (int i = 0; i < 1000000; i++)
{
StudentDTO itemT = emitMapper.Map(_student);
}
StopTest(sw);
}
Tests results on my PC:
Test Auto Mapper:22322 ms
Test Implicit Operator:310 ms
Test Property Copy:250 ms
Test Emit Mapper:281 ms
You can get emit and auto -mappers from here:
http://emitmapper.codeplex.com/
http://automapper.codeplex.com/
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…