Linq连接效率问题
// Loop each users profile
using (DataClassesDataContext db = new DataClassesDataContext())
{
var q = (from P in db.tblProfiles orderby P.UserID descending select new { LastUpdated = P.ProfileLastUpdated, UserID = P.UserID }).ToList();
foreach(var Rec in q){
string Username = db.tblForumAuthors.SingleOrDefault(author => author.Author_ID == Rec.UserID).Username;
AddURL(("Users/" + Rec.UserID + "/" + Username), Rec.LastUpdated.Value, ChangeFrequency.daily, 0.4);
}
}
这是我的站点地图,打印系统上每个用户配置文件的 URL。但是假设我们有 20,000 个用户,用户名查询是否会显着减慢速度?
我习惯于在 SQL 查询中加入联接,但将其与主查询分开并放在循环中似乎效率很低,除非它编译得很好。
// Loop each users profile
using (DataClassesDataContext db = new DataClassesDataContext())
{
var q = (from P in db.tblProfiles orderby P.UserID descending select new { LastUpdated = P.ProfileLastUpdated, UserID = P.UserID }).ToList();
foreach(var Rec in q){
string Username = db.tblForumAuthors.SingleOrDefault(author => author.Author_ID == Rec.UserID).Username;
AddURL(("Users/" + Rec.UserID + "/" + Username), Rec.LastUpdated.Value, ChangeFrequency.daily, 0.4);
}
}
This is for my sitemap, printing a URL for each users profile on the system. But say we have 20,000 users, is the Username query going to slow this down significantly?
I'm used to having the join in the SQL query, but having it separated from the main query and in the loop seems like it could be inefficient unless it compiles it well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它可能会慢得难以忍受。在您的情况下,这将向数据库发出 20,000 个单独的 SQL 查询。由于查询同步运行,因此每次迭代都会产生服务器通信开销。延迟会累积得相当快。
加入吧。
顺便说一下,如果缺少
author
,SingleOrDefault(...).Username
将抛出 NullReferenceException。最好使用Single()
或检查你的逻辑。It will probably be unbearably slow. In your case this will issue 20,000 separate SQL queries to the database. Since the queries run synchronously, you will incur the server communication overhead on each iteration. The delay will accumulate quite fast.
Go with a join.
By the way,
SingleOrDefault(...).Username
will throw a NullReferenceException if theauthor
is missing. Better useSingle()
or check your logic.如果在设计 DataContext 时在数据库中正确设置了约束,那么设计者应该在您的 Profile 和 Author 类中生成一对一的成员。
如果没有,您可以在设计器中手动完成。
然后你就可以做这样的事情:
If you have constranints set up correctly in your database while designing the DataContext, then the designer should generate a one-to-one members in your Profile and Author classes.
If not, you can do it manually in designer.
Then you will be able to do something like this:
加入吧!
避免不必要的数据库访问,加入并一次性获得您需要的一切!
Do the JOIN!
Save yourself from unnecessary database access, join and get everything you need in a single shot!