【发布时间】:2009-11-05 18:21:33
【问题描述】:
我的代码中有如下一行:
potentialCollisionsX.Intersect(potentialCollisionsY).Distinct().ToList();
通过分析,我确定它占用了我大约 56% 的时间。我需要弄清楚如何提供有效的实现。我试过了
List<Extent> probableCollisions = new List<Extent>();
for (int j = 0; j < potentialCollisionsX.Count; j++)
{
if (potentialCollisionsY.Contains(potentialCollisionsX[j]) && !probableCollisions.Contains(potentialCollisionsX[j]))
{
probableCollisions.Add(potentialCollisionsX[j]);
}
}
但这只会降低到 42%。非常感谢优化或替代想法。
编辑:有人要求提供有关 Extent 类的信息,我想不出比提供类定义更好的方式来向他们提供信息。
private enum ExtentType { Start, End }
private sealed class Extent
{
private ExtentType _type;
public ExtentType Type
{
get
{
return _type;
}
set
{
_type = value;
_hashcode = 23;
_hashcode *= 17 + Nucleus.GetHashCode();
}
}
private Nucleus _nucleus; //Nucleus is the main body class in my engine
public Nucleus Nucleus
{
get
{
return _nucleus;
}
set
{
_nucleus = value;
_hashcode = 23;
_hashcode *= 17 + Nucleus.GetHashCode();
}
}
private int _hashcode;
public Extent(Nucleus nucleus, ExtentType type)
{
Nucleus = nucleus;
Type = type;
_hashcode = 23;
_hashcode *= 17 + Nucleus.GetHashCode();
}
public override bool Equals(object obj)
{
return Equals(obj as Extent);
}
public bool Equals(Extent extent)
{
if (this.Nucleus == extent.Nucleus) //nucleus.Equals does an int comparison
{
return true;
}
return false;
}
public override int GetHashCode()
{
return _hashcode;
}
}
Edit2:似乎使用哈希集可以使我的这部分代码达到我需要的性能,所以感谢你的帮助!
【问题讨论】:
-
您能否详细说明 Extent 类包含哪些数据以及如何比较它们?我考虑了几种不同的算法,具体取决于它们是否只能进行相等比较;比较较小/较大;或转换为某种二进制字符串(如整数值或其他东西)。
-
您知道对于同一个 Nucleus,两个不同的范围(一个是起始范围,另一个是结束范围)将返回 Equals()==true,但哈希码不同?
-
嗯,我应该可以解决这个问题。
-
我记得为什么我现在不这样做,我不需要区分范围类型。回滚...
-
那么你也应该让你的哈希码不区分它们。否则所有依赖它的算法都会失败
标签: c# .net optimization list intersection