今天,我将向您展现这些EF Core中一个很酷的功能,经过使用显式编译的查询,提升查询性能。git
不过在介绍具体内容以前,须要说明一点,EF Core已经对表达式的编译使用了缓存;当您的代码须要重用之前执行的查询时,EF Core将使用哈希查找并从缓存中返回已编译的查询。github
关于这一点,您能够查阅github上面的代码QueryCompiler.cs数据库
不过,您可能但愿直接对查询进行编译,跳过哈希的计算和缓存查找。咱们能够经过在EF
静态类中下面两个方法来实现:缓存
这些方法容许您定义一个已编译的查询,而后经过调用一个委托调用它。函数
若是您对表达式的哈希计算感兴趣,能够看一看它的实现,很是复杂,ExpressionEqualityComparer.cs。性能
为了不由于数据库查询产生测试结果的差别,咱们这里使用内存数据库,它开销更小,同时也能够避免数据库优化执行计划以及缓存所带来的问题。测试
实体定义之前数据库DbContext
定义实体优化
在这咱们定义一个Category
实体类型,很是简单,只有两个属性。ui
public class Category { public Guid Id { get; set; } public string Name { get; set; } }
数据库DbContextspa
在FillCategories
方法中,将内存数据库中增长三条记录。
public class TestDbContext : DbContext { public TestDbContext(DbContextOptions<TestDbContext> options) : base(options) { } public DbSet<Category> Categories { get; set; } public void FillCategories() { var foodCategory = new Category { Id = Guid.NewGuid(), Name = "Food" }; Categories.AddRange(foodCategory, new Category { Id = Guid.NewGuid(), Name = "Drinks" }, new Category { Id = Guid.NewGuid(), Name = "Clothing" }, new Category { Id = Guid.NewGuid(), Name = "Electronis" }); SaveChanges(true); } }
测试代码
public class CompileQueryTest { private Func<TestDbContext, Guid, Category> _getCategory = EF.CompileQuery((TestDbContext context, Guid id) => context.Categories.FirstOrDefault(c => c.Id == id)); private readonly TestDbContext _dbContext; public CompileQueryTest() { var options = new DbContextOptionsBuilder<TestDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options; var context = new TestDbContext(options); context.FillCategories(); _dbContext = context; } private readonly Guid _queryId = Guid.NewGuid(); [Benchmark] public void CompiledQuery() { _ = _getCategory(_dbContext, _queryId); } [Benchmark] public void UnCompiledQuery() { _ = _dbContext.Categories.FirstOrDefault(c => c.Id == _queryId); } }
为了更加接近测试结果,咱们在构造函数中建立TestDbContext
对象以及填充数据库。
测试结果
咱们使用Benchmark.Net进行基准测试,测试结果以下:
Method | Mean | Error | StdDev |
---|---|---|---|
CompiledQuery | 10.59 us | 0.0580 us | 0.0543 us |
UnCompiledQuery | 79.55 us | 0.7860 us | 0.7353 us |
通过编译的查询比未编译过的查询存在接近8倍的差距。若是您对这个功能感兴趣,不防本身测试一下。