刚刚读过
"Any class that implements the IEqualityComparer interface is expected to provide the implementation for the Equals method." - (Delphi DocWiki)
和
"Any class that implements the IEqualityComparer interface is expected to provide the implementation for the GetHashCode method." - (Delphi DocWiki)
如果我创建 TDictionary<TObject, TObject>
,TDictionary 的性能会如何?并且不实现 IEqualityComparer?
我还没有找到默认实现(在 Delphi 2009 中)。那么它们的键的哈希码是如何计算的呢?
如果它只是字典条目键中对象的内存地址,是否会按顺序执行对给定条目的搜索?
最佳答案
使用 TObject 键时,默认实现将表现得非常好。相等被定义为对象标识,与测试 if A=B
相同。哈希值只是引用的地址 - 它的效率再高不过了。
代码如下所示:
function TObject.Equals(Obj: TObject): Boolean;
begin
Result := Obj = Self;
end;
function TObject.GetHashCode: Integer;
begin
Result := Integer(Self);
end;
在散列字典中查找不涉及搜索。这是一个高效的 O(1) 操作。我认为你应该阅读Wikipedia文章。
关于performance - TDictionary<TObject, TObject> 的默认 IEqualityComparer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5315258/