當我們在類成員函數中頻繁操作類成員變量時(例如,在for循環中反覆調用成員變量),我們可以把該成員變量複製到成員函數中,成爲局部變量,幫助編譯器更好的優化循環體,因爲成員變量對編譯器來說更容易追蹤。
例如下面程序,在operator()的for循環中反覆調用成員變量m_i:
// main.cpp
#include <iostream>
#include "tbb/tbb.h"
using namespace std;
using namespace tbb;
#define NUM 100000000
class Body {
public:
Body():m_i(1) {}
~Body() {}
void operator()() {
int sum = 0;
for (int i = 0; i < NUM; i++) {
sum += m_i; // 反覆調用成員變量m_i
}
}
int m_i;
};
int main(int argc, char** args) {
tick_count start = tick_count::now();
Body bd;
bd();
cout << "consume time is:" << (tick_count::now() - start).seconds() << endl;
return 0;
}
執行時間大約爲0.38s。
在operator()中把成員變量m_i複製到局部變量i上:
#include <iostream>
#include "tbb/tbb.h"
using namespace std;
using namespace tbb;
#define NUM 100000000
class Body {
public:
Body():m_i(1) {}
~Body() {}
void operator()() {
int sum = 0;
int i = m_i;
for (int i = 0; i < NUM; i++) {
sum += i; // 反覆調用局部變量i
}
}
int m_i;
};
int main(int argc, char** args) {
tick_count start = tick_count::now();
Body bd;
bd();
cout << "consume time is:" << (tick_count::now() - start).seconds() << endl;
return 0;
}
執行時間大約爲0.35s,和沒有局部處理相比快了0.03s,這是一個較大的性能提高。