gpt4 book ai didi

c# - Linq to SQL to Linq 编译性能

转载 作者:行者123 更新时间:2023-12-02 22:31:29 26 4
gpt4 key购买 nike

string id = (from c in context.Users
where c.u_id == Id
select c.u_id).SingleOrDefault();

1) 我如何使用 Linq 编译查询提高上述性能。我们仅限于使用 .NET 3.5。

2) 以百分比的形式对上述代码使用编译的 linq 查询会带来多少性能提升?

最佳答案

您将通过以下方式创建编译查询:

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 查询实际上更慢,因为编译的开销并不能弥补速度的提高。您需要衡量以确定这是否值得付出努力。

请注意,如果您知道您只有一个唯一 ID,则还可以仅通过使用 FirstOrDefault() 而不是 SingleOrDefault() 来加速原始查询.

关于c# - Linq to SQL to Linq 编译性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12182926/

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