什么时候应该使用CompiledQuery? [英] When should I use a CompiledQuery?

查看:155
本文介绍了什么时候应该使用CompiledQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张表:

-- Tag

ID  | Name
-----------
1   | c#
2   | linq
3   | entity-framework

我有一个类将具有以下方法:

I have a class that will have the following methods:

IEnumerable<Tag> GetAll();
IEnumerable<Tag> GetByName();

在这种情况下,我应该使用编译查询吗?

Should I use a compiled query in this case?

static readonly Func<Entities, IEnumerable<Tag>> AllTags =
    CompiledQuery.Compile<Entities, IEnumerable<Tag>>
    (
        e => e.Tags
    );

然后我的 GetByName 方法将是: / p>

Then my GetByName method would be:

IEnumerable<Tag> GetByName(string name)
{
    using (var db = new Entities())
    {
        return AllTags(db).Where(t => t.Name.Contains(name)).ToList();
    }
}

其中生成一个 SELECT ID ,名称FROM标签并执行其中代码。或者我应该避免在这种情况下使用 CompiledQuery

Which generates a SELECT ID, Name FROM Tag and execute Where on the code. Or should I avoid CompiledQuery in this case?

基本上我想知道什么时候我应该使用编译查询。另外,在一个网站上,他们只为整个应用程序编译一次?

Basically I want to know when I should use compiled queries. Also, on a website they are compiled only once for the entire application?

推荐答案

您应该使用当所有以下内容都为真时,CompiledQuery


  • 查询将不止一次执行,参数值

  • 查询是非常复杂的,表达式评估和生成视图的成本是重要的(尝试和错误)

  • 您是不使用LINQ功能,如 IEnumerable< T> .Contains(),它不适用于 CompiledQuery li>
  • 您已经简化了查询,这样可以提供更大的性能优势。

  • 您不打算进一步撰写查询结果(例如,限制或项目),其具有反编译的作用。

  • The query will be executed more than once, varying only by parameter values.
  • The query is complex enough that the cost of expression evaluation and view generation is "significant" (trial and error)
  • You are not using a LINQ feature like IEnumerable<T>.Contains() which won't work with CompiledQuery.
  • You have already simplified the query, which gives a bigger performance benefit, when possible.
  • You do not intend to further compose the query results (e.g., restrict or project), which has the effect of "decompiling" it.

CompiledQuery 第一次执行查询执行工作。它对第一次执行没有好处。像任何性能调优一样,一般来说,避免这种情况,直到你确定要修复一个实际的性能热点。

CompiledQuery does its work the first time a query is executed. It gives no benefit for the first execution. Like any performance tuning, generally avoid it until you're sure you're fixing an actual performance hotspot.

2012更新: EF 5将自动执行此操作(请参阅实体框架5:控制自动查询编译)。所以添加你没有使用EF 5到上面的列表。

2012 Update: EF 5 will do this automatically (see "Entity Framework 5: Controlling automatic query compilation") . So add "You're not using EF 5" to the above list.

这篇关于什么时候应该使用CompiledQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆