I have a function that's called hundreds of thousands of times per update, and i need to optimize it. Now, i generally follow the "don't optimize too soon" rule but this is a critical function that virtually all of my code's time is spent in, so anything you can suggest would help. I'm also not that familiar with any sort of tips and tricks that can be used to optimize XNA or c# code. Can you help me?
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;