我的代码中有如下一行:
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:似乎使用哈希集可以使我的这部分代码达到我需要的性能,所以感谢您的帮助!
最佳答案
Intersect
无论如何返回不同的元素,调用 Distinct()
不必要。这至少会占用您的一些时间。
还有,你真的需要调用ToList
吗? ?然后你对结果做了什么?
顺序重要吗?如果没有,您应该考虑使用 HashSet<T>
而不是 List<T>
对于您的“手动”代码。 (也可能为 HashSet<T>
创建一个 potentialCollisionsY
。)这将使 Contains
成为调用速度更快,至少在集合足够大的情况下...
顺便说一句,不要相信documentation for Intersect
- 这是 wrong about the order of operations (至少在 .NET 3.5 中)
关于c# - 性能相交和不同的元素提取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1679258/