【发布时间】:2017-02-25 13:41:02
【问题描述】:
我有以下嵌套循环:
(...)
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)] 属性吗?
【问题讨论】:
-
我认为代码审查网站更适合你。
-
我还建议先查看他们的help center。
-
“不喜欢循环内的条件,因为性能可能会降低” 但作为安慰,它可以节省异常情况。
-
@OusmaneDiaw 我的代码有一些错误,我已经更正了。立即查看。
-
为什么你需要对 r 和 c 的多个值进行循环。 if(p.y