我在循环中遇到高性能问题。我不确定如何优化代码,说实话。使用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>();
}