为什么字典查找比递归搜索慢?

时间:2013-10-07 06:42:06

标签: c# recursion dictionary

我正在尝试优化TreeNodeCollection中的节点搜索。原始方法使用递归方法:

public UGTreeNode FindNode(BaseId nodeId, TreeNodeCollection nodes)
{
    foreach (UGTreeNode n in nodes)
    {
        if (n.node_info.Description.base_id.Id == nodeId.Id &&
            n.node_info.Description.base_id.RootId == nodeId.RootId &&
            n.node_info.Description.base_id.SubId == nodeId.SubId)
            return n;
        UGTreeNode n1 = FindNode(nodeId, n.Nodes);
        if (n1 != null)
            return n1;
    }
    return null;
}

我尝试将所有节点存储在Dictionary中并使用Dictionary.TryGetValue搜索节点:

public UGTreeNode FindNode(BaseId nodeId, TreeNodeCollection nodes)
{
    UGTreeNode res;
    _nodesCache.TryGetValue(nodeId.Id, out res);
    return res;
}

但事实证明,第二种方法比第一种方法慢(大约慢了10倍)。这有什么可能的原因?

1 个答案:

答案 0 :(得分:1)

当您总是搜索树中的第一个项目时,递归可能会更快。它还取决于Equals的{​​{1}}实现或您在字典中使用的比较器。在递归方法中,您有参考比较。该词典使用BaseIdGetHashCode

你是如何衡量表现的?