在.NET GetHashCode方法中,很多地方都使用.NET 方法.特别是在快速查找集合中的项目或确定相等性时.是否有关于如何GetHashCode为我的自定义类实现覆盖的标准算法/最佳实践,因此我不会降低性能?
我有一个方法,使用递归遍历树并更新项目.
目前该方法处理所有项目需要很长时间,所以我开始优化.其中包括使用字典而不是为每个项目执行数据库查询.
字典定义为
System.Collections.Generic.Dictionary<EffectivePermissionKey, MyData>
Run Code Online (Sandbox Code Playgroud)
密钥类型定义为
private struct EffectivePermissionKey
{
// http://blog.martindoms.com/2011/01/03/c-tip-override-equals-on-value-types-for-better-performance/
public override bool Equals(object aObject)
{
if (aObject == null)
return false;
else
return aObject is EffectivePermissionKey && Equals((EffectivePermissionKey)aObject);
}
public bool Equals(EffectivePermissionKey aObject)
{
return this.ID == aObject.ID && this.OrchardUserID == aObject.OrchardUserID;
}
public override int GetHashCode()
{
// http://stackoverflow.com/a/32502294/3936440
return unchecked(ID.GetHashCode() * 23 * 23 + OrchardUserID.GetHashCode() * 23);
}
public int ID;
public int OrchardUserID;
}
Run Code Online (Sandbox Code Playgroud)
该方法运行时,需要大约5000次递归才能更新所有项目.
最初没有字典需要大约100秒.
使用带有int键的字典替换数据库查询的第一种方法需要22秒 …
.net ×1
algorithm ×1
c# ×1
dictionary ×1
gethashcode ×1
hashcode ×1
performance ×1
recursion ×1