gpt4 book ai didi

c# - LinqToSql 预编译查询有什么好处?

转载 作者:太空狗 更新时间:2023-10-29 22:24:39 25 4
gpt4 key购买 nike

我正在查看 LINQPad 提供的样本 LINQ 查询,这些查询取自 Nutshell 书中的 C# 4.0,并遇到了一些我从未在 LINQ to SQL 中使用过的东西...编译查询。

这是确切的例子:

// LINQ to SQL lets you precompile queries so that you pay the cost of translating
// the query from LINQ into SQL only once. In LINQPad the typed DataContext is
// called TypeDataContext, so we proceed as follows:

var cc = CompiledQuery.Compile ((TypedDataContext dc, decimal minPrice) =>
from c in Customers
where c.Purchases.Any (p => p.Price > minPrice)
select c
);

cc (this, 100).Dump ("Customers who spend more than $100");
cc (this, 1000).Dump ("Customers who spend more than $1000");

像这样预编译 LINQ to SQL 查询到底给我带来了什么?我会从比这个稍微复杂一点的查询中获得性能提升吗?这甚至在实际实践中使用过吗?

最佳答案

简而言之,当您需要多次运行单个查询时,预编译查询可为您带来性能提升。

这是一些 information关于 LINQ To SQL 性能。

I’ve read in several places that compiling your LINQ will help, but I have never heard anyone say how drastic the speed improvement can be. For example, in one of my favorite books (LINQ in Action) by Fabrice Marguerie and others, he quotes on page 296 a blog post by Rico Mariani titled DLINQ (Linq to SQL Performance (Part 1) as saying using a compiled query offers nearly twice the performanced of a non-compiled query, and goes on to say that it brings the performance to within 93% of using a raw data reader. Well, suffice it to say I never ran the test myself. I could have lived with twice, but not 37 times.

alt text

So, from this, it seems that you should always compile your LINQ to SQL queries. Well, that’s not quite true. What I’m recommending is that if you have a reason to execute the same query over and over you should strongly consider compiling. If for example, you are just making a LINQ to SQL call once, there is no benefit because you have to compile it anyway. Call it ten times? Well, you will have to decide for yourself.

关于c# - LinqToSql 预编译查询有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3873984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com