因为对表达式树有点兴趣,出于练手的目的,试着写了一个深拷贝的工具库。支持.net standard2.0或.net framework4.5及以上。
GitHub地址https://github.com/blurhkh/DeepCopier
nuget地址https://www.nuget.org/packages/DeepCopier
使用方法如下:
首先创建几个测试用的类型
public class Author { public string Name { get; set; } } public class Book { public string Title { get; set; } public Author Author { get; set; } public List<string> Tags { get; set; } } public class BookDTO { public string Title { get; set; } public Author Author { get; set; } public List<string> Tags { get; set; } }
Book book = new Book { Author = new Author { Name = "Author" }, Title = "Title", Tags = new List<string> { "dotnet-core", "c#" } }; // 用法1 深拷贝一个对象 Book book2 = Copier.Copy(book); // 或一个IEnumerable<T>的实现类实例(目前仅支持一维数组和ICollection<T>的实现类) HashSet<Book> books = new HashSet<Book>() { book, book }; HashSet<Book> books2 = Copier.Copy(books); // 用法2 新建目标类型实例,并将源对象的属性值拷贝至目标对象的对应属性 BookDTO bookDTO = Copier.Copy<Book, BookDTO>(book); // 用法3 将源对象的属性值拷贝至已存在的目标对象的对应属性 BookDTO target = new BookDTO(); Copier.Copy(book, target);
同类的工具库比如较为常见的AutoMapper和一个Reflection.Emit操作IL写的DeepCopy(https://www.nuget.org/packages/DeepCopy/)
接下来进行一下和他们的性能对比,测试数据采用上面的Book类型,循环次数为1000万次。
测试数据如下:
Book book = new Book { Author = new Author { Name = "Author" }, Title = "Title", Tags = new List<string> { "dotnet-core", "c#" } };
测试内容如下(本人PC的CPU为I7 4790k,不同库的测试代码分别跑在不同的程序里):
首先和AutoMapper进行对比
BookDTO bookDTO = null; Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 1000000; i++) { bookDTO = DeepCopier.Copier.Copy<Book, BookDTO>(book); } Console.WriteLine($"DeepCopier costed {sw.ElapsedMilliseconds} ms at 1st time."); sw.Restart(); for (int i = 0; i < 1000000; i++) { bookDTO = DeepCopier.Copier.Copy<Book, BookDTO>(book); } // 因为有了前一次的缓存,这里速度会更快 Console.WriteLine($"DeepCopier costed {sw.ElapsedMilliseconds} ms at 2nd time."); Console.ReadLine();
// AutoMapper需要提前配置 AutoMapper.Mapper.Initialize(config => { config.CreateMap<Book, BookDTO>(); }); BookDTO bookDTO = null; Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 1000000; i++) { bookDTO = AutoMapper.Mapper.Map<Book, BookDTO>(book); } Console.WriteLine($"AutoMapper costed {sw.ElapsedMilliseconds} ms at 1st time."); sw.Restart(); for (int i = 0; i < 1000000; i++) { bookDTO = AutoMapper.Mapper.Map<Book, BookDTO>(book); } Console.WriteLine($"AutoMapper costed {sw.ElapsedMilliseconds} ms at 2nd time."); Console.ReadLine();
// DeepCopy只支持对自身类型的拷贝 Book temp = null; Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 1000000; i++) { temp = DeepCopy.DeepCopier.Copy(book); } Console.WriteLine($"DeepCopy costed {sw.ElapsedMilliseconds} ms at 1st time."); sw.Restart(); for (int i = 0; i < 1000000; i++) { temp = DeepCopy.DeepCopier.Copy(book); } // AutoMapper第二次并不会比第一次快 Console.WriteLine($"DeepCopy costed {sw.ElapsedMilliseconds} ms at 2nd time."); Console.ReadLine();