[英]How to speed up an incredibly slow loop through a List of
我有以下方法從數據庫中檢索銷售數據。
Db 在 1.5 到 1.9 秒內返回數據,我希望更快,但我必須一次一步地在方法中操作數據,因為我不知道如何以最終形式返回它從查詢中,這當然是最有效的方法。
由於結果(結果類型是 AuctionDatum 列表)計數很少會超過 1-200 個結果,我認為這種方法現在就足夠了......不是
db 運行如上所述,但循環需要將近 4-5 秒,而對於這次測試,它只有 25 條記錄!! (25 個需要轉換為 $ 的 4 個,我沒有測量那個方法的時間)
方法
public async Task<CarSalesData> GetCarSalesDataAsync(int modelId)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
var results = await GetVehicleAuctionDataForModelAsync(modelId);
var cnt = results.Count;
var csd = new CarSalesData
{
ModelName =
$"{results[0].Vehicle.Model.Manufacturer.ManufacturerName} {results[0].Vehicle.Model.ModelYear} {results[0].Vehicle.Model.ModelName}"
};
var dates = new List<string>();
var values = new List<double>();
stopwatch.Stop();
var elt = stopwatch.Elapsed;
stopwatch.Start();
foreach (var result in results)
{
if (result.AuctionCurrency == "USD")
{
dates.Add(result.AuctionDate.ToString("MM/dd/yyyy"));
values.Add(Convert.ToDouble(result.SoldPrice));
}
else
{
dates.Add(result.AuctionDate.ToString("MM/dd/yyyy"));
values.Add(Convert.ToDouble(VehicleManagerHelpers.GetPriceInUSD(Convert.ToDecimal(result.SoldPrice), result.AuctionCurrency, result.AuctionDate))); }
}
csd.SaleDates = dates;
csd.SalesValues = values;
stopwatch.Stop();
var elt1 = stopwatch.Elapsed;
//the value of err below is:: The data retrieval method took 01.8641257 seconds and the loop took 05.5960528 seconds
var err = $"The data retrieval method took {elt} seconds and the loop took {elt1} seconds";
return csd;
}
數據庫方法
public async Task<IList<VehicleAuctionData>> GetVehicleAuctionDataForModelAsync(int modelId)
{
return await _context.AuctionDatum
.Include(u => u.Vehicle)
.Include(u => u.Vehicle.Model)
.Include(u => u.Vehicle.Model.Manufacturer)
.Where(u => u.Vehicle.ModelId == modelId && u.SoldPrice !=null)
.OrderBy(u => u.AuctionDate)
.ToListAsync();
}
任何幫助使其更有效地運行將不勝感激。
如果您只需要幾個屬性,請創建一個包含您需要的那些屬性的模型,然后select
進去。 例如:
public async Task<IList<VehicleAuctionData>> GetVehicleAuctionDataForModelAsync(int modelId)
{
return await _context.AuctionDatum
.Include(u => u.Vehicle)
.Include(u => u.Vehicle.Model)
.Include(u => u.Vehicle.Model.Manufacturer)
.Where(u => u.Vehicle.ModelId == modelId && u.SoldPrice !=null)
.Select(u => new SmallerObject{
Manufacturer = u.Vehicle.Model.Manufacturer.Name,
AuctionDate = u.AuctionDate,
AuctionCurrency = u.AuctionCurrency,
// add properties as needed here
})
.OrderBy(u => u.AuctionDate)
.ToListAsync();
}
使用 Linq,查詢將被修剪為僅返回滿足輸出所需的那些值。 根據對象的重量,這可能會減少從數據庫返回的數據量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.