對象memory
有簽名的方法爲什麼要存儲一個引用而不是兩次請求我的應用程序太慢?
BinaryPattern const& getPattern(unsigned int index) const;
我在使用這個下面的for循環:
for (unsigned int k = 0; k < memory->size(); k++) {
const BinaryPattern s = memory->getPattern(k);
w += s.at(i) * s.at(j);
}
這是非常緩慢的。出人意料的是,我發現下面的速度要快得多:
for (unsigned int k = 0; k < memory->size(); k++) {
w += memory->getPattern(k).at(i) * memory->getPattern(k).at(j);
}
「getPattern()」沒有做任何的計算,它非常簡單,只是返回存儲在向量模式。
爲什麼當我將參考存儲在一個變量中時速度太慢了?我最初這樣做是爲了加快速度,因爲我預計兩次檢索參考速度會更慢。
將其更改爲'常量BinaryPattern&S =內存 - > getPattern(K);' – 2012-08-15 13:27:10
@sbi:我錯了有關的具體細節(我不知道很多關於C++ )。我指的是複製構造函數http://en.wikipedia.org/wiki/Copy_constructor,你在你的答案中已經解釋過。 – nhahtdh 2012-08-15 13:36:10