2015-09-06 82 views
0

下面是有問題的代碼段。我們正在嘗試將項目與項目屬性集合進行匹配。下面的代碼工作,我們返回我們需要的,但它很慢。我們很好奇最好的辦法是做什麼。任何幫助是極大的讚賞。我們也對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() 
     }); 
    } 
} 
+0

你的代碼的一部分,是exaclty慢GetItemsAsync或GetItemProperties或者在selectedProperties.since我們不知道的是裏面有什麼代碼的methods.it的努力幫助?我唯一可以說的就是int selectedProperties.Count()強制轉換十進制一次。 – Arash

+0

也許想想掩飾。 – SimpleVar

回答

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*/) 
+0

如果你編寫一個新的方法來獲取所有需要的項目及其屬性,而不是先獲取它們的id,然後根據id獲取屬性,那麼你甚至可以歸結爲一個SQL Access。我完全同意Kuosa先生所說的大量數據庫訪問(取決於項目的數量)會顯着降低性能。 – Martin

相關問題