【发布时间】:2011-03-01 22:02:35
【问题描述】:
免责声明:我对 linq 几乎没有经验。
我的工作任务之一是维护一个电子商务网站。昨天,我们的一位客户开始抱怨当他们尝试为谷歌创建提要文件时会发生超时。事实证明,如果用户有超过 9,000 个项目要放入他们的提要文件中,我们的代码至少需要一分钟才能执行。
我无法通过运行调试器找到问题的根源,所以我启动了一个分析器 (ANTS) 并让它完成它的工作。它找到了我们问题的根源,一个包含一些 linq 代码的 foreach 循环。代码如下:
var productMappings = GoogleProductMappingAccess.GetGoogleProductMappingsByID(context, productID);
List<google_Category> retCats = new List<google_Category>(numCategories);
int added = 0;
//this line was flagged by the profiler as taking 48.5% of total run time
foreach (google_ProductMapping pm in (from pm in productMappings orderby pm.MappingType descending select pm))
{
if (pm.GoogleCategoryId.HasValue && pm.GoogleCategoryId > 0)
{
//this line was flagged as 36% of the total time
retCats.Add(pm.google_Category);
}
else if (pm.GoogleCategoryMappingId.HasValue && pm.GoogleCategoryMappingId > 0)
{
retCats.Add(pm.google_CategoryMapping.google_Category);
}
else
{
continue;
}
if (++added >= numCategories)
{
break;
}
}
你们有经验的开发者有什么想法吗?我正在尝试用 sql 替换所有 linq,但我不确定这是否是这里最好的做法(如果它是用 linq 编写的,那肯定是有原因的)。
【问题讨论】:
-
不要在循环中执行 linq。将结果存储在变量中并使用它。
-
提高 DataContext.CommandTimeout 以快速修复。
-
可能不再需要这样做了。如果可能的话,喜欢避免它
-
@mad:这根本不会有任何区别。
标签: c# linq optimization