我正在努力嘗試一下。我讀過它可能會影響性能,但不如此代碼塊對我的機器有影響。Try-catch影響XNA的性能
foreach (Crew CurrentBall in CrewList)
{
if (CurrentBall != WhiteBall)
{
double distance = 0;
try
{
distance = Math.Sqrt((CurrentBall.Rectangle.X - SnakeArray[CurrentBall.SnakePosition - 1].Rectangle.X)
* (CurrentBall.Rectangle.X - SnakeArray[CurrentBall.SnakePosition - 1].Rectangle.X)
+ (CurrentBall.Rectangle.Y - SnakeArray[CurrentBall.SnakePosition - 1].Rectangle.Y)
* (CurrentBall.Rectangle.Y - SnakeArray[CurrentBall.SnakePosition - 1].Rectangle.Y));
}
catch
{
distance = Math.Sqrt((CurrentBall.Rectangle.X - WhiteBall.Rectangle.X)
* (CurrentBall.Rectangle.X - WhiteBall.Rectangle.X)
+ (CurrentBall.Rectangle.Y - WhiteBall.Rectangle.Y)
* (CurrentBall.Rectangle.Y - WhiteBall.Rectangle.Y));
}
if (distance < 75 && CurrentBall != WhiteBall)
{
if (CurrentBall.IsFollowingWhite == false)
{
NumberOfBallsFollowingWhite++;
CrewCatch.Play();
Score += 5;
ReduceMovementSpeed();
ApplyText(CurrentBall);
SnakeArray[NumberOfBallsFollowingWhite] = CurrentBall;
CurrentBall.SnakePosition = NumberOfBallsFollowingWhite;
}
CurrentBall.Follow(SnakeArray[CurrentBall.SnakePosition - 1]);
CurrentBall.IsFollowingWhite = true;
}
}
}
它工作得很好,直到我用try-catch。我也嘗試沒有Math.Sqrt,但它沒有任何改善。
try/catch塊中最昂貴的部分是實際捕獲(投擲,堆棧跟蹤等)。我認爲'if/else'會更適合你的情況。 – Stefan
你應該清理輸入,不要依賴catch來執行不同的邏輯。 –
你爲什麼使用try/catch?該機制永遠不會用於遊戲。 –