我正在尝试优化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倍)。这有什么可能的原因?
答案 0 :(得分:1)
当您总是搜索树中的第一个项目时,递归可能会更快。它还取决于Equals
的{{1}}实现或您在字典中使用的比较器。在递归方法中,您有参考比较。该词典使用BaseId
和GetHashCode
。
你是如何衡量表现的?