用于优化

时间:2012-03-18 00:56:52

标签: c# linq optimization time-complexity

我正在尝试优化此代码:

   foreach (string id in ids)
   {
     MyClass x = myDictionary[id];
     foreach (var map in Maps)
     {
       if ( x.id == map.SourceId || x.id == map.DestionationId)
       {
           //add id to a hashset
       }
     }
   }

如果ids.count为1600且Maps.Count为300 000,则需要大约10分钟才能处理。

我已经尝试过LINQ,但结果并不是很好:

   var allIds = Maps.select(map => map.SourceId).Union(Maps.select(map => map.DestinationID)).Distinct();
   var toAdd = from id in Ids
               join mapId in AllIds on id equals mapid
               select id;
  //create hashset based on  toAdd collection.

有人能指出一个更好的解决方案吗?如果可能的话,解释一下为什么linq在这种情况下不会更快?

由于

1 个答案:

答案 0 :(得分:5)

你有O(countIds * countMaps)的复杂性,如果你将所有地图放入由源和目的地索引的2个词典中,你将获得O(countIds + countMaps)。