short[] rgbValues = new short[shorts];
.......
  for (int y_value = 0; y_value < BitmapHeight; y_value++)
  {
  xyValue = y_value * bmp_width + x_value;
  if (rgbValues[xyValue] == 0)
  {
  TempBuffer[j] |= OrBytes[i];
  if ((TempBuffer[j] == 0xfd) || (TempBuffer[j] == 0xfe) || (TempBuffer[j] == 0xff))
  {
  TempBuffer[j + 1] = (byte)(TempBuffer[j] ^ 0x20);
  TempBuffer[j] = 0xfd;
  j++;
  }
  }
  i++;
  if (i == 8)
  {
  j++;
  i = 0;
  }
  }图上的红色部分导致速度很慢,不注释了蓝色部分,整个代码需要1400多毫秒;注释了蓝色部分,整个代码仍需要1300多毫秒。问题就出在红色的语句上,请问该如何提速?

解决方案 »

  1.   

    条件执行是会稍微慢一点(影响了CPU指令预测),但我不认为是你程序慢的原因。比如你代码中局部缓存的影响肯定更大:
    for (int y_value = 0; y_value < BitmapHeight; y_value++)
    {
      xyValue = y_value * bmp_width + x_value;
      ...
    }
    如果扫描线比较长,处理下一个y_value可能导致cache miss,而进行内存读取比条件执行慢了好多。最后,局部缓存的影响也不见得就是你程序慢的主要原因,最有可能的是你的算法有问题。
      

  2.   

    代码的优化                   比如代码                            if(condition1){                                     Dosomething1();       }                            if(condition2){                                     Dosomething2 ();      }                   显然代码                            if(condition1){                                     Dosomething1 ();      }                            else if(condition2){                                     Dosomething2 ();      }                   有更高的效率(condition2与condition1互斥)。                   在比如代码                            If(Trim(str)==”str1”|| Trim(str)==”str2”){                                     Dosomething();}显然没有代码         string strTemp= Trim(str);                            if(strTemp ==”str1”|| strTemp ==”str2”){                                     Dosomething();}效率高。
      

  3.   

    你把这个rgbValues由short[]改为int[]应该会好些~
      

  4.   

    经过测试发现int[]没有提高速度。感觉需要用指针访问数组,请问如何改成指针访问数组呢?