繁体   English   中英

编译查询和普通查询对我实体框架似乎没有区别

[英]Compiled query and normal query, seems no difference for me entity framework

我停留在已编译查询和普通查询中,自3天以来一直在进行此操作,但是找不到线索为什么会发生这种情况,请帮帮我。

我有一张表是“要约”,其中包含3500条记录。 我写了两种查询,一种是编译查询,另一种是普通查询。 参见下面的代码。

编译查询。

public static class TestCompiled
{        
    private static readonly Func<MyEntity, DateTime, IEnumerable<Offer>> activeOfferCQ =
        CompiledQuery.Compile(
          (MyEntity context, DateTime currentTime) =>
              context.Offers.Where(o => (o.Organization == null || (o.Organization != null && o.Organization.IsActive == true))));

    public static IEnumerable<Offer> GetBesicActiveOffers(MyEntity DBContext, DateTime currentTime)
    {
        return activeOfferCQ.Invoke(DBContext, currentTime);
    }
}

这是我的已编译查询,并且我已经创建了控制台应用程序以比较这些已编译查询和正常查询,以下是代码。

履行

MyEntity context = new MyEntity ();

for (int i = 0; i < 5; i++)
{
    var temp = i + 1;
    sp.Start();
    List<Offer> objOffers = context.Offers.Where(x =>(x.Organization == null || (x.Organization != null && x.Organization.IsActive == true))).ToList();
    Console.WriteLine("SrN: " + (temp) + "  Q1= " + sp.Elapsed.Milliseconds + "    Record Count=" + objOffers.Count());
    sp.Stop();

    sp.Start();
    List<Offer> objList = TestCompiled.GetBesicActiveOffers(context, curtime).ToList();
    Console.WriteLine("SrN: " + (temp) + "  Q2= " + sp.Elapsed.Milliseconds + "    Record Count=" + objList.Count());
    sp.Stop();
    Console.WriteLine("______________________________________________________________");
    Console.WriteLine();
    //if (i == 0)
    Thread.Sleep(5000);
}

结果。

检查结果: 在此处输入图片说明

当我发现普通查询的运行速度比编译查询快时,因为我们知道编译查询比普通查询快,请帮助我我做错了什么。 我是否在编译查询中缺少任何内容。

由于时间和变化如此之小,我认为查询的编译时间(看起来很简单)不会产生任何重大变化。

顾名思义,EF中的已编译查询避免了编译查询的开销。 它实际上并没有帮助数据库查询时间或数据传输时间。 由于查询的编译时间(即SQL语句的创建时间)可以忽略不计,因此您基本上看不到任何差异(或很小的差异)。

附带说明:您在已编译查询中使用的DateTime参数在查询本身中未使用...我不认为在这种精确的情况下它确实会影响查询编译时间,但是对于性能测试而言,似乎很奇怪。 您应该尝试在相同条件下衡量性能。

PS :使用DbContext和EF(从版本5开始)时,不直接支持已编译的查询,已经在其认为合适的地方缓存了查询(它们称为“自动编译的查询”)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM