下面我有嵌套循环: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
_“不喜欢条件循环内的性能可能会下降”_但作为一种安慰,它可以节省异常。 –