Linq to SQL to Linq编译性能 [英] Linq to SQL to Linq compiled performance
问题描述
string id = (from c in context.Users
where c.u_id == Id
select c.u_id).SingleOrDefault();
1)我如何使用上面的Linq符合条件的查询来提高上面的性能. 我们仅限使用.NET 3.5.
1)How i can improve the performance for the above using Linq complied query for the above. We are limited to use .NET 3.5 only.
2)对百分比而言,使用上述代码的linq查询的性能提升会是多少?
2)What will be performance gain using a complied linq query for the above code in terms of percentage?
推荐答案
您可以通过以下方式创建编译后的查询:
You would create the compiled query via:
Func<YourContextType, int, string> query = CompiledQuery.Compile(
(YourContextType context, int id) =>
context.Users.Where(u => u.u_id == id).Select(u => u.u_id)
.SingleOrDefault()
);
然后将其用作:
string resultId = query(context, Id);
对于性能提升,这可能很重要,但也可能很小.这实际上取决于执行查询的速度以及您可以多久重复使用一次已编译的查询.在许多情况下,使用cmopiled查询实际上会比较慢,因为编译的开销无法弥补速度的提高.您需要进行度量以确定这是否值得付出努力.
As for the performance gain, this may be significant, but it may also be minimal. It really depends on how quick the query is being performed, and how often you can reuse the compiled query. In many cases, using the cmopiled query is actually slower, as the overhead of compilation doesn't make up for the speed gains. You would need to measure to determine if this is worth the effort.
请注意,如果您知道自己只有一个唯一的ID,也可以仅使用FirstOrDefault()
而不是SingleOrDefault()
来加快原始查询的速度.
Note that, if you know you only have one unique ID, you can also potentially speed up your original query merely by using FirstOrDefault()
instead of SingleOrDefault()
.
这篇关于Linq to SQL to Linq编译性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!