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.ggressiveinlining)]属性?

该方法调用,如果语句真的不会非常损害您的性能进一步优化。因此,如果您的程序运行缓慢,您应该更多地专注于制作更可读的代码,并搜索真正的瓶颈。

但我也有一个有关您的代码的问题,似乎您永远不会在循环中更改x和y,所以您无法将界限和美元支票带到循环外。

做得好,使其更可读性,并且可以正确命名方法。由于for循环仅执行3次,对于值-1、0和1的值,性能并没有像您一样少的循环迭代。

每次过早和不必要优化的代码可读性。

最新更新