EF Core通过显式编译提高查询性能

2022-04-17 04:07:28

今天,我将向您展示这些EF Core中一个很酷的功能,通过使用显式编译的查询,提高查询性能。

不过在介绍具体内容之前,需要说明一点,EF Core已经对表达式的编译使用了缓存;当您的代码需要重用以前执行的查询时,EF Core将使用哈希查找并从缓存中返回已编译的查询。

不过,您可能希望直接对查询进行编译,跳过哈希的计算和缓存查找。我们可以通过在EF静态类中下面两个方法来实现:

EF.CompileQuery()EF.CompileAsyncQuery()

这些方法允许您定义一个已编译的查询,然后通过调用一个委托调用它。

为了避免因为数据库查询产生测试结果的差异,我们这里使用内存数据库,它开销更小,同时也可以避免数据库优化执行计划以及缓存所带来的问题。

实体定义以前数据库DbContext

定义实体

在这我们定义一个Category实体类型,非常简单,只有两个属性。

    public class Category    {        public Guid Id { get; set; }        public string Name { get; set; }    }

数据库DbContext

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进行基准测试,测试结果如下:

MethodMeanErrorStdDev
CompiledQuery10.59 us0.0580 uwww.easck.coms0.0543 us
UnCompiledQuery79.55 us0.7860 us0.7353 us

经过编译的查询比未编译过的查询存在接近8倍的差距。如果您对这个功能感兴趣,不防自己测试一下。

到此这篇关于EF Core通过显式编译提高查询性能的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。