偶然發現,遍歷vector時,使用兩種看上去沒什麼差異的方法,性能上卻有很大的差別。ios
#include <iostream> #include <vector> class CPoint{ public: int x; int y; }; int VectorRead_0(const CPoint* arr, size_t size) { int result = 0; for(size_t i = 0; i < size; i ++){ result += (arr[i].x + arr[i].y); } return result; } int VectorRead_1(const vector<CPoint> &arr) { int result = 0; for(size_t i = 0; i < arr.size(); i ++){ result += (arr[i].x + arr[i].y); } return result; } int VectorRead_2(const vector<CPoint> &arr) { size_t size = arr.size(); int result = 0; for(size_t i = 0; i < size; i ++){ result += (arr[i].x + arr[i].y); } return result; } int VectorRead_3(const vector<CPoint> &arr) { size_t size = arr.size(); const CPoint* pArr = &arr[0]; int result = 0; for(size_t i = 0; i < size; i ++){ result += (pArr[i].x + pArr[i].y); } return result; } void TestVectorRead() { const int arrSize = 100000; vector<CPoint> arr(arrSize); int i, nLoopCount = 100000; DWORD start,end; int result; for(i = 0; i < arrSize; i ++){ arr[i].x = i % 3; arr[i].y = i % 4; } start = ::GetTickCount(); result = 0; for (i = 0; i < nLoopCount; i++){ result += VectorRead_0(&arr[0], arrSize); } end = ::GetTickCount(); cout << "VectorRead_0 takes: " << end - start << " result: " << result << std::endl; start = ::GetTickCount(); result = 0; for (i = 0; i < nLoopCount; i++){ result += VectorRead_1(arr); } end = ::GetTickCount(); cout << "VectorRead_1 takes: " << end - start << " result: " << result << std::endl; start = ::GetTickCount(); result = 0; for (i = 0; i < nLoopCount; i++){ result += VectorRead_2(arr); } end = ::GetTickCount(); cout << "VectorRead_2 takes: " << end - start << " result: " << result << std::endl; start = ::GetTickCount(); result = 0; for (i = 0; i < nLoopCount; i++){ result += VectorRead_3(arr); } end = ::GetTickCount(); cout << "VectorRead_3 takes: " << end - start << " result: " << result << std::endl; }
執行結果(運行環境:ThinkPad T430,VS2013):oop
VectorRead_0 takes: 5663 result: -769903776
VectorRead_1 takes: 0 result: -769903776
VectorRead_2 takes: 0 result: -769903776
VectorRead_3 takes: 0 result: -769903776性能
可見,VectorRead_0性能很是糟糕,極可能編譯器對vector有特殊的優化。測試
另外,用一樣的方式測試了vector在寫入狀況下的性能,幾種方法在性能上並無明顯差別。優化