C# 在ANTs profiler info的帮助下识别性能瓶颈
此代码运行速度非常慢:C# 在ANTs profiler info的帮助下识别性能瓶颈,c#,linq,profiler,red-gate-ants,C#,Linq,Profiler,Red Gate Ants,此代码运行速度非常慢: public static class DB { readonly static InlineSql sql = new InlineSql(); public static IEnumerable<LabItem> GetLabItemsFromLabLineItems(IEnumerable<LabLineItem> items) { /*
public static class DB
{
readonly static InlineSql sql = new InlineSql();
public static IEnumerable<LabItem> GetLabItemsFromLabLineItems(IEnumerable<LabLineItem> items)
{
/*
* Business Rule :
* The sproc used to retrieve lab line items has no way of "grouping" lab items out of line items.
* To compensate, the sproc orders its results by IDCode, we group everything and use the first of each grouping to represent that ID Code.
* That very same item is also the first item in its Items property.
* */
return items
.GroupBy(c => c.IDCode , c => c, (c, d) => d.First())
.Select(c => new LabItem(c.IDCode, c.OrderGuid, c.Name, c.SignificantDtm, c.Status, c.Description, items.Where(d => string.Compare(d.IDCode, c.IDCode, true) == 0 )));
}
}
ANTS说,
Select
和string.Compare
调用被命中9000万次,因为对于主列表中的每个项目,它将再次搜索整个列表
每个主要的9000次迭代都会导致9000次额外的迭代,因此必须至少调用81000000次字符串.Compare
我建议构建分组的缓存,然后使用它来构造LabItem
也许是这样的:
var groupedItems = items.GroupBy(c => c.IDCode);
return items.Select(c =>
new LabItem(c.IDCode, c.OrderGuid, c.Name, c.SignificantDtm, c.Status, c.Description,
groupedItems.Where(d => string.Compare(d.Key, c.IDCode, true) == 0 ).SelectMany(group => group)));
ANTS说,
Select
和string.Compare
调用被命中9000万次,因为对于主列表中的每个项目,它将再次搜索整个列表
每个主要的9000次迭代都会导致9000次额外的迭代,因此必须至少调用81000000次字符串.Compare
我建议构建分组的缓存,然后使用它来构造LabItem
也许是这样的:
var groupedItems = items.GroupBy(c => c.IDCode);
return items.Select(c =>
new LabItem(c.IDCode, c.OrderGuid, c.Name, c.SignificantDtm, c.Status, c.Description,
groupedItems.Where(d => string.Compare(d.Key, c.IDCode, true) == 0 ).SelectMany(group => group)));
嗯,潜在的嵌套枚举数可能会产生严重的性能问题。。。。在蚂蚁队,我一直认为命中率是“实际”命中率。这看起来很有帮助:@Cal279-我怀疑它正在进入代理。我不会插手代表们。我越过那条线。也许这就是区别。@P.Brian.Mackey调用的委托确实会添加到hit-count.Hmmm中,潜在的嵌套枚举数可能会造成严重的性能问题。。。。在蚂蚁队,我一直认为命中率是“实际”命中率。这看起来很有帮助:@Cal279-我怀疑它正在进入代理。我不会插手代表们。我越过那条线。也许这就是区别。@P.Brian.Mackey确实增加了命中率。+1这看起来很有希望。我只需要弄清楚如何将
IEnumerable
转换回IEnumerable
,否则我将不得不更改LabItem构造函数,我认为我不应该在这里这样做。构造函数需要什么类型iGroup
实现了IEnumerable
,因此如果构造函数需要IEnumerable
,它应该编译。只需添加选择Many
。回答得很好。非常感谢,太好了!谢谢你得到最后一点。+1这看起来很有希望。我只需要弄清楚如何将IEnumerable
转换回IEnumerable
,否则我将不得不更改LabItem构造函数,我认为我不应该在这里这样做。构造函数需要什么类型iGroup
实现了IEnumerable
,因此如果构造函数需要IEnumerable
,它应该编译。只需添加选择Many
。回答得很好。非常感谢,太好了!谢谢你得到最后一点。