【发布时间】:2010-12-11 20:40:17
【问题描述】:
我有一个每次更新调用数十万次的函数,我需要对其进行优化。现在,我通常遵循“不要过早优化”的规则,但这是一个关键功能,几乎我所有的代码时间都花在了上面,所以你可以提出的任何建议都会有所帮助。我也不熟悉任何可用于优化 XNA 或 c# 代码的技巧和窍门。你能帮帮我吗?
if (linearPosition.Y < _min.Y || linearPosition.Y > _max.Y)// the nonlinear space commisioned doesn't cover it so that's the behavior i want, same case with next line
{
return linearPosition;
}
if (linearPosition.X < _min.X || linearPosition.X > _max.X)
{
return linearPosition;
}
PositionData[] fourNearestPoints = new PositionData[4]
{
new PositionData {distance = float.MaxValue},
new PositionData {distance = float.MaxValue},
new PositionData {distance = float.MaxValue},
new PositionData {distance = float.MaxValue}
};
for (int x = 0; x < _restPositions.GetLength(0); x++)
{
for (int y = 0; y < _restPositions.GetLength(1); y++)
{
PositionData temp = new PositionData
{
indexX = x,
indexY = y,
value = _restPositions[x,y],
distance = (linearPosition - _restPositions[x,y]).Length()
};
if (temp.distance < fourNearestPoints[0].distance)
{
fourNearestPoints[3] = fourNearestPoints[2];
fourNearestPoints[2] = fourNearestPoints[1];
fourNearestPoints[1] = fourNearestPoints[0];
fourNearestPoints[0] = temp;
}
}
}
Vector2 averageRestVector = new Vector2((fourNearestPoints[0].value.X +
fourNearestPoints[1].value.X +
fourNearestPoints[2].value.X +
fourNearestPoints[3].value.X) / 4,
(fourNearestPoints[0].value.Y +
fourNearestPoints[1].value.Y +
fourNearestPoints[2].value.Y +
fourNearestPoints[3].value.Y) / 4);
Vector2 averageDeformedVector = new Vector2((_deformedPositions[fourNearestPoints[0].indexX, fourNearestPoints[0].indexY].X +
_deformedPositions[fourNearestPoints[1].indexX, fourNearestPoints[1].indexY].X +
_deformedPositions[fourNearestPoints[2].indexX, fourNearestPoints[2].indexY].X +
_deformedPositions[fourNearestPoints[3].indexX, fourNearestPoints[3].indexY].X) / 4,
(_deformedPositions[fourNearestPoints[0].indexX, fourNearestPoints[0].indexY].Y +
_deformedPositions[fourNearestPoints[1].indexX, fourNearestPoints[1].indexY].Y +
_deformedPositions[fourNearestPoints[2].indexX, fourNearestPoints[2].indexY].Y +
_deformedPositions[fourNearestPoints[3].indexX, fourNearestPoints[3].indexY].Y) / 4);
Vector2 displacement = averageDeformedVector - averageRestVector;
return linearPosition + displacement;
【问题讨论】:
-
查看更新的答案不是每次都创建
temp -
添加了关于 LengthSquared 的注释
-
另外 - 我认为你的代码有问题......如果我们测试的点不是 最接近的,但比第二个更接近,会发生什么-最近的?您可能还需要 3 次针对 _1、_2、_3 的距离测试
-
我将变量距离初始化为 float.MaxValue,然后仅在距离低于我假设的列表中的第一项时对变量进行洗牌(丢弃最后一项并将每个项向上移动一项)是最接近的。因此,在任何给定时间,列表中的第 3 项只有在比列表中的第 4 项更近但比第 2 项更远的情况下才能到达那里。
-
这里有一个额外的想法;我想知道您是否可以在您考虑的最大距离周围构建一个框(即,一个正方形,其“半径”为最近点_3 的距离(inc. sqrt))。然后,您可以仅通过 x/y 排除候选点。每当您找到一个新的最近点_3 时,您都需要维护该框(使其更小)。
标签: c# .net optimization xna