1

我在循环内遇到高性能问题。老实说,我不确定如何优化代码。使用 Visual Studio 性能资源管理器,我设法修复了一些我遇到的错误,但现在问题似乎是由于这个特定的 for 循环正在执行的循环数。

这是来自 Visual Studio 的屏幕截图:

Visual Studio 性能屏幕截图

我猜测,由于int i = 0被标记,性能问题是由于大量循环造成的。Alsp,我知道这ExecuteReader被标记为高性能,但我认为我无法改变它,我的意思是这是我从数据库收到的请求。

编辑

代码:

public IQueryable<Match> GetMatches()
{
    DLTxOdds dlTxOdds = new DLTxOdds();
    IQueryable<Match> matches = dlTxOdds.GetMatches();
    List<Match> mList = new List<Match>();

    // For each retrieved match check whether it contains any sure bets
    foreach (Match m in matches)
    {
        List<SureBet> matchSureBets = new List<SureBet>();

        // Get sport of match
        m.sport = dlTxOdds.GetMatchSport(m.sportid);
        // Get orders of match, ordered by the odd type id
        m.matchOffers = dlTxOdds.GetMatchOffers(m.matchid).OrderBy(o => o.ot).ToList();

        int tempID = -1;
        List<Offer> tempMatchOffersList = new List<Offer>();
        // For every match offer get its respective bookmaker, odds and odd type
        for (int i = 0; i < m.matchOffers.Count; i++)
        {
            m.matchOffers[i].bookmaker = dlTxOdds.GetBookmaker(m.matchOffers[i].bid);
            m.matchOffers[i].odds = dlTxOdds.GetOfferOdds(m.matchOffers[i].offer_id);
            m.matchOffers[i].oddType = dlTxOdds.GetOddType(m.matchOffers[i].ot);

            // Filter the match offers so that offers with the same odd type id are checked for sure bets
            tempID = m.matchOffers[i].ot;
            // if current index is last one we cannot check for the next element therefore add to list and check for sure bets
            if (i + 1 != m.matchOffers.Count)
            {
                // if next odd type in list is different, check for sure bets
                if (m.matchOffers[i + 1].ot != tempID)
                {
                    tempMatchOffersList.Add(m.matchOffers[i]);
                    // Get sure bets
                    matchSureBets.AddRange(GetSureBets(tempMatchOffersList));
                    tempMatchOffersList = new List<Offer>();
                }
                // else add to temporary list
                else
                    tempMatchOffersList.Add(m.matchOffers[i]);
            }
            else
            {
                tempMatchOffersList.Add(m.matchOffers[i]);
                // Get sure bets
                matchSureBets.AddRange(GetSureBets(tempMatchOffersList));
            }
        }

        if (m.matchOffers.Count() != 0)
        {
            // if match has any sure bets add to list...
            if (matchSureBets.Count() != 0)
            {
                m.sureBets = matchSureBets.Where(s => s.max == true).OrderByDescending(s => s.profit).ToList();
                mList.Add(m);
            }
        }
    }

    mList = mList.OrderByDescending(m => m.sureBets[0].profit).ToList();
    return mList.AsQueryable<Match>();
}
4

0 回答 0