下面我有嵌套循環:C#:一個循環內優化條件
(...)
while (some_condition)
{
(...)
MyObject p = new MyObject(i, j);
for (int r = -1; r <= 1; r++)
{
for (int c = -1; c <= 1; c++)
{
// check matrix bounds
if (p.y + r <= 0 || p.y + r >= bound1 ||
p.x + c <= 0 || p.x + c >= bound2)
{
continue;
}
else if (matrix[p.y + r][p.x + c]=='$') // at this point no IndexOutOfBounds may be raised as it is checked in previous condition
{
continue;
}
AddItem(r, c);
}
}
}
myObject的是,其中包括具有以下attirbutes類:
public class MyObject {
public int x;
public int y;
public MyObject(int x, int y)
{
this.x = x;
this.y = y;
}
// Other methods ....
}
所以我擔心的表現,我的意思是,我不喜歡循環中的條件,因爲性能可能會下降,所以我該如何優化?
此外,我想使代碼更易讀,所以我有如下改寫它:
while (some_condition)
{
(...)
MyObject p = new MyObject(i, j);
for (int r = -1; r <= 1; r++)
{
for (int c = -1; c <= 1; c++)
{
if (!IsOutOfBounds(r, c, p) && !IsDollar(r, c, p))
{
AddItem(r, c);
}
}
}
}
private bool IsOutOfBounds(int r, int c, MyObject p)
{
return (p.y + r <= 0 || p.y + r >= bound1 ||
p.x + c <= 0 || p.x + c >= bound2);
}
private bool IsDollar(int r, int c, MyObject p)
{
// matrix is global
return (matrix[p.y + r][p.x + c]=='$');
}
但現在,循環中調用函數也降低性能,所以如何做,內聯函數?我是否必須在兩個函數之前添加[MethodImpl(MethodImplOptions.AggressiveInlining)]屬性?
我認爲代碼審查網站會更好。 –
我還建議先查看他們的[幫助中心](http://codereview.stackexchange.com/help)。 – Incomputable
_「不喜歡條件循環內的性能可能會下降」_但作爲一種安慰,它可以節省異常。 –