【问题标题】:Fastest of the following Mapping objects (Dictionary,Tuple,KeyvaluePair)以下映射对象中最快的(字典、元组、键值对)
【发布时间】:2013-04-08 14:52:23
【问题描述】:

目前我有这样的映射设置

//Identifiers to save (currently)
Dictionary<string, Dictionary<string, string>> toSaveIdentifiers =
    new Dictionary<string, Dictionary<string, string>>(); //

但是,我想为其添加一个额外的维度,因为我错过了要添加的额外属性。

我正在尝试设置某种形式的映射,该映射会在程序中频繁填充,并且还会在整个程序中进行查找。我想知道这样做的最佳方法是什么。

//Identifiers to save (tuple)
Dictionary<Tuple<string,string>, Dictionary<string, string>> toSaveIdentifiers =
    new Dictionary<Tuple<string, string>, Dictionary<string, string>>(); //

//Identifiers to save (adding another dictionary dimension)
Dictionary<string, Dictionary<string,Dictionary<string, string>>> toSaveIdentifiers =
    new Dictionary<string, Dictionary<string, Dictionary<string, string>>>(); //

//Identifiers to save (adding keyvaluepair)
Dictionary<KeyValuePair<string,string>, Dictionary<string, string>> toSaveIdentifiers =
    new Dictionary<KeyValuePair<string, string>, Dictionary<string, string>>(); //

当我填充它/查找时,我会做类似的事情。

   // check identifier map dictionary
    if (dictionary.Keys.Contains(identifier))
    {
        if (dictionary[identifier].Keys.Contains(currency))
        {
            //stuff
        }
        else
        {
            //stuff
        }
    }
    else
    {
            //more stuff
    }

查找的最佳方法是什么?

【问题讨论】:

  • 您绝对应该使用有意义的属性名称创建自己的自定义 class/struct,而不是 DictionaryTupleKeyValuePair 以及这些的任意组合。
  • 在嵌套泛型集合层次结构的迷宫中的某个地方,也许自文档类不会被证明更有用?
  • 同意...当您或其他人将来返回维护此代码时,现在花费的时间将超过回报。
  • @Ramie 没有一个!最好不要编写代码,而不是那种风格的代码......

标签: c# optimization data-structures dictionary hashmap


【解决方案1】:

由于您的标识符似乎都是字符串类型,您总是可以将它们全部连接成一个大字符串并将其用作键。然后,您只需要做一个,而不是做嵌套的包含。就存储不同级别的标识符而言,它也会更加灵活。

即给定一个 2 级密钥,它将是

string ident = level1Identifier + "." + level2Identifier;

(使用 string.format() 或 StringBuilder 会更高效,但这段代码更便于解释)

还要考虑加入字符应该是您知道不会出现在任何级别标识符中的东西,以避免混淆或意外重复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-25
    • 2019-04-28
    • 2011-12-27
    • 2012-01-11
    • 2012-05-30
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    相关资源
    最近更新 更多