對象的屬性訪問效率的新發現

來源:互聯網
上載者:User

     最近做一個映像問題的程式,需要對一幅比較大的圖進行遍曆,將每個像素資訊提取出來,用了BitMap及BitmapData。由於圖片很大(2000*1000),每次操作都要等很久,全套操作下來居然需要12秒還多,代碼最佳化了好多次,始終沒有質的改變,今天抱著試一試的態度將迴圈內的對象屬性訪問全部提取到迴圈外,速度居然一下就上去了,表達能力有限,這裡直接看代碼:

沒有最佳化
        public void Binary()
        {
            for (int j = 0; j < originalImage.Height; j++)
            {

                for (int i = 0; i < originalImage.Width; i++)
                {
                    brightness = imageBrightness[i + j * originalImage.Width];
                    if (brightness < 128)
                    {
                      binaryImageData[i + j * originalImage.Width] = 1;

                  }
                  else
                  {
                      binaryImageData[i + j * originalImage.Width] = 0;
                  }
                }
            }
        }

 

上面的代碼中,迴圈內每次都要訪問originalImage.Width等對象屬性,現在將其提到迴圈外

 

最佳化過的代碼
        public void Binary()
        {
            int h = originalImage.Height;
            int w = originalImage.Width;
            for (int j = 0; j < h; j++)
            {

                for (int i = 0; i < w; i++)
                {
                    brightness = imageBrightness[i + j * w];
                    if (brightness < 128)
                    {
                      binaryImageData[i + j * w] = 1;

                  }
                  else
                  {
                      binaryImageData[i + j * w] = 0;
                  }
                }
            }
        }

 

     就是在迴圈外用一個簡單變數代替對象的屬性,經過測試,我的程式在最佳化過後速度居然提高了20多倍,遍曆3000*2000的圖從接近40秒降到了1500毫秒,效果顯著。

    簡單分析,訪問屬性效率不高可能有兩個原因

    1.屬性內部在get時要有其他運算,佔用時間

    2.取一個對象的屬性,要對對象定位(不知道怎麼形容,可能叫做定址更準確),經過迴圈的累加效應,這部分時間越來越多。

    以上只是個人猜測,歡迎大家幫我分析出準確原因

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.