我有以下嵌套循环:
(...)
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是一个低于其他类别的类:
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)]属性的两个函数之前使用?
答案 0 :(得分:1)
方法调用和if语句不会真正损害您的性能,除非您每秒调用该方法1000次或者您是在一台非常旧的机器上,而且编译器将进一步优化。因此,如果您的程序运行缓慢,您应该更专注于使代码更具可读性并搜索真正的瓶颈。
但是我也有一个关于你的代码的问题,看起来你永远不会在你的循环中改变x和y,所以你不能在你的循环之外带来越界和美元检查。
答案 1 :(得分:1)
干得好,使其更具可读性,并确保方法的正确命名。因为for
循环只被执行了3次,对于值-1,0和1,性能并没有真正进入它,只需要很少的循环迭代。
每次过早和不必要的优化的代码可读性。