dot trace profile, why is my in memory fetch being flagged as slow

假如想象 提交于 2020-01-05 03:34:18

问题


How would i improve this?

the profile is suggesting that fetching data from a list is slow

public List<RowDataDto> Rows { get; set; }

public RowDataDto GetRow(int rowNdx)
{
      var row = Rows.SingleOrDefault(x => x.LineNumber == rowNdx);
      return row;   
}

The list will on average contain around 1000 items im just benchmaching to see how it performance.

its saying the slowest part is fetching from an in memory list.

Rows is populated well before GetRow is called.

LineNumber is an int32

PS - I have just installed dotTrace and im very new to it so I may not be understanding how to use the tool properly. I have simple tests. I start ".Net Process" tell my test to run and at some point hit take snapshot.

If you have used this tool before please guide me.


回答1:


If you have in-memory list and you want to perform certain lookup a lot of times on it - it's better to use dictionary instead of list. For ease of use you can expose readonly collection of that dictionary values if you need to (it's usually not good to expose dictionary as a public member):

private Dictionary<int, RowDataDto> _rows;
public IReadOnlyCollection<RowDataDto> Rows {get {return _rows.Values;}}

public RowDataDto GetRow(int rowNdx)
{
    var row = _rows.ContainsKey(rowNdx) ? _rows[rowNdx] : null;
    return row;   
}

Also note that using SingleOrDefault is rarely good. If your list is not expected to contain duplicates - just use FirstOrDefault. SingleOrDefault will have to go through the whole list to ensure that there are no duplicates, which in such case means it will always go through the whole list.



来源:https://stackoverflow.com/questions/44694925/dot-trace-profile-why-is-my-in-memory-fetch-being-flagged-as-slow

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!