Dictionary <string,string =“”>值查找性能</string,>

时间:2015-03-08 18:26:32

标签: c# performance dictionary lookup pseudocode

我正在开展一个小型项目,但遇到了性能障碍。

我有Dictionary<string, string>()

我有string[]

假设我的Dictionary有50,000个条目,我的string[]有30,000个条目。

我想从我的Keys收集Dictionary value.ToCharArray().OrderBy(x => x)value.ToCharArray().OrderBy(x => x)等于我string[]的{​​{1}}。

我尝试通过将KeyValue值的长度与string[]中的值进行比较来减少我必须查看的Dictionary对的数量,但这并没有真正获得我的表现。

有没有人有想法如何提高此查找的效果?

谢谢!

扩展伪代码:

var stringToLookUp = GetSomeStrings(s.ToString()).Select(x => x).OrderBy(x => x).ToArray();
var aDictionaryOfStringString = GetDictionary(Resources.stringList);

var results = new List<string>();

foreach (var theString in stringToLookUp.Where(aString=> aString.Length > 0))
{
    if (theString.Length > 0)
    {
        var theStringClosure = theString;

        var filteredKeyValuePairs = aDictionaryOfStringString.Where(w => w.Value.Length == theStringClosure.Length && !results.Contains(w.Key)).ToArray();
        var foundStrings = filteredKeyValuePairs.Where(kv => kv.Value.ToCharArray().OrderBy(c => c).ToArray().SequenceEqual(theStringClosure))
                .Select(kv => kv.Key)
                .ToArray();
        if (foundStrings.Any()) results.AddRange(foundStrings);
    }
}

2 个答案:

答案 0 :(得分:2)

我认为主要问题是你在每次迭代中迭代整个字典 - 这是O(N ^ 2)。根据您修改的密钥(来自字典或数组)更好地构建hashset,并迭代第二个。这是O(N)。

// some values
var dictionary = new Dictionary<string, string>();
var fields = new string[]{};


string[] modifiedFields = new string[fields.Length];
for(var i =0; i < fields.Length; i++)
{
  modifiedFields[i] = new string(fields[i].ToCharArray().OrderBy(x =>x).ToArray());
}
var set = new HashSet<string>(modifiedFields);
var results = new List<string>();
foreach(var pair in dictionary)
{
  string key = new string(pair.Value.ToCharArray().OrderBy(x =>x).ToArray());
  if (set.Contains(key))
  {
    results.Add(pair.Key);
  }
}

答案 1 :(得分:0)

你可以试试这个

var stringToLookUp = GetSomeStrings(s.ToString()).Select(x => x).OrderBy(x => x).ToArray();
var aDictionaryOfStringString = GetDictionary(Resources.stringList);

var results = aDictionaryOfStringString.Where(kvp => stringToLookUp.Select(s => s.OrderBy(x => x)).Contains(kvp.Value.OrderBy(x => x))).Select(kvp => kvp.Key).ToList();