最近一直在使用 Petapoco https://github.com/CollaboratingPlatypus/PetaPoco +Entity Framework Core 结合开发一套系统.
使用 EFCore 进行 Code First 编码, 使用 PMC 命令生成数据库表的信息.
使用 Petapoco 进行数据库的常规操作. 并且结合 https://github.com/asherber/PetaPoco.SqlKata 的使用, 减少了编写 SQL 语句的工作量, 对提升开发效率有很大的帮助. Petapoco 对数据库的支持非常的全, 包括常规的一下数据库: SQL Server,SQL Server CE,MS Access,SQLite,MySQL,MariaDB,PostgreSQL,Firebird DB 和 Oracle. 当然 SQL Server 为默认的支持. PetaPoco.SqlKata 支持的数据库也是非常全的, 包括: SqlServer, MySQL, Postgres, Firebird, SQLite, Oracle.
在数据库操作过程中, 发现每个 Controller 的 Index 页面加载的非常缓慢, 加载完成大约需要 5s 的时间, 在浏览器端等待的时间相对来说是非常长的一个时间. 对于出现的问题终于有时间进行解决一下了.
先来看一下未使用 Order By 加载页面的耗时情况, 第一个图中涉及的表的主键为 guid 类型, 第二个图中涉及的主键为 ulong 类型, 对于不同的主键进行分页查询时也有较大影响.
图一
图二
使用 Order by 加载页面的耗时情况
图三
图四
对出现的问题, 使用 StopWatch 进行监视运行时间的长短, 使用了分页的两种方法, 区别是否加 Order By 语句, 组成成如下四种情况:
- PageAsync Order by
- PageAsync
- Page Order by
- Page
代码如下:
- Stopwatch stop = new Stopwatch();
- stop.Start();
- var pages = await _context.PageAsync<productdto>(page, itemsPerPage, "order by id");
- stop.Stop();
- _logger.Information($"Order By Async 查询的执行时间:{stop.Elapsed}");
- stop.Restart();
- var pages2 = await _context.PageAsync<productdto>(page, itemsPerPage );
- stop.Stop();
- _logger.Information($"Async 查询的执行时间:{stop.Elapsed}");
- //_logger.Information($"SQL:{_context.LastSQL}");
- stop.Restart();
- var ps = _context.Page<productdto>(page, itemsPerPage, "order by id");
- stop.Stop();
- _logger.Information($"Order By 查询的执行时间:{stop.Elapsed}");
- stop.Restart();
- var ps2 = await _context.PageAsync<productdto>(page, itemsPerPage);
- stop.Stop();
- _logger.Information($"查询的执行时间:{stop.Elapsed}");
- stop.Restart();
- var x = _mapper.Map<page<productviewmodel>>(pages);
- stop.Stop();
- _logger.Information($"Mapper 的执行时间:{stop.Elapsed}");
运行后台输出的日志信息, 可以看到对于是否加 Order By 对查询耗时的影响是非常大的, 对是否使用异步方法对耗时也有部分的影响
对于上述的四种情况再次使用 Benchmark 进行一次性能测试, 对使用的数据表的实体类不在列出
- namespace PetaPocoPageBenchMark
- {
- class Program
- {
- static void Main(string[] args)
- {
- var summary = BenchmarkRunner.Run<petapocopage>();
- Console.WriteLine("Hello World!");
- }
- }
- public class PetapocoPage
- {
- public static IDatabase Database =>
- new Database(DatabaseConfiguration.Build()
- .UsingConnectionString(
- "server=192.168.88.3;port=3306;uid=root;pwd=biobase;database=BiobaseProductionQrCode;")
- .UsingProvider<mariadbdatabaseprovider>());
- [Benchmark]
- public void PageOrderBy()
- {
- Database.Page<productmanufacturelinedetaildto>(1, 20, "order by CreateDate");
- }
- [Benchmark]
- public void Page()
- {
- Database.Page<productmanufacturelinedetaildto>(1, 20);
- }
- [Benchmark]
- public void PageOrderByAsync()
- {
- Database.PageAsync<productmanufacturelinedetaildto>(1, 20, "order by CreateDate");
- }
- [Benchmark]
- public void PageAsync()
- {
- Database.PageAsync<productmanufacturelinedetaildto>(1, 20);
- }
- }
- }
对性能测试结果可以看到, 使用 Order By 对性能的影响确实是非常大.
来源: https://www.cnblogs.com/sesametech-netcore/p/11726779.html