【问题标题】:Best way to get all items that match quickly快速获取所有匹配项的最佳方法
【发布时间】:2015-09-06 17:52:54
【问题描述】:

以下是相关代码的 sn-p。我们正在尝试将一个项目与项目属性的集合进行匹配。下面的代码有效,我们返回了我们需要的东西,但是它很慢。我们很好奇这样做的最佳方法是什么。任何帮助是极大的赞赏。我们也对 SQL 中的选项持开放态度。谢谢!

var items = await GetItemsAsync(repository, a, b);
// Next we need to get all of the properties for those items. 
var results = new List<Result>();
foreach(var c in items)
{
   c.Properties = await GetItemProperties(repository, c.Id);
   var matchedProperties = selectedProperties.Where(si => c.Properties.Any(i => i.Id == si.Id));
   if(matchedProperties.Count() > 0)
   {
       results.Add(new Result(c)
       {
           MatchedProperties = matchedProperties,
           Relevance = (decimal)matchedProperties.Count() / (decimal)selectedProperties.Count()
       });
   }
}

【问题讨论】:

  • 您的代码的哪一部分非常慢?GetItemsAsync 或 GetItemProperties 或在 selectedProperties 中的什么位置。因为我们不知道这些方法中的代码是什么。很难提供帮助。我唯一能说的是只需 int selectedProperties.Count() 转换十进制一次。
  • 或许可以考虑使用位掩码。

标签: c# sql model-view-controller


【解决方案1】:

我认为性能不佳的主要原因是您正在检查项目的结果并在每个项目中执行新的 sql 查询。所以你不能确定会有多少 sql 查询命中。查询数量为 1 + 项目结果。

如果你改成这样呢:

var items = await GetItemsAsync(repository, a, b);

var ids = items.Select(c => c.id);

var properties = await GetItemsProperties(repository, ids);

 // map items and properties after this without sql queries

如果你这样做,你将只有两 (2) 个 sql 查询。

sql 可能是这样的:

SELECT * FROM properties_table WHERE itemId IN (/*your ids here: 1, 2, 3 etc*/) 

【讨论】:

  • 如果你编写一个新方法来获取所有需要的项目及其属性,而不是先获取它们的 id,然后根据 id 获取属性,也许你甚至可以使用 SQL Access )。我完全同意 Kuosa 先生的观点,即大量的数据库访问(取决于项目的数量)会显着降低性能。
猜你喜欢
  • 2017-07-07
  • 2012-06-15
  • 1970-01-01
  • 2022-08-24
  • 1970-01-01
  • 2020-11-04
  • 1970-01-01
  • 2012-05-02
  • 1970-01-01
相关资源
最近更新 更多