我一直在使用gprof在一個簡單版本的向量上分配堆上的內存(沒有實際上是動態的 - 僅用於測試目的)運行測試。事情是,看看我看到'new []'和'delete []'之間的巨大差異 - 因爲我實際上向vector中插入了值(使用[]運算符)。 做上述,我得到了類似的結果:刪除[]工作比新的[]慢嗎?
% cumulative self self total
time seconds seconds calls s/call s/call name
0.92 0.55 0.01 1 5.03 5.03 MyVector::~MyVector()
0.00 0.55 0.00 1 0.00 0.00 MyVector::MyVector(int)
但如果我只是分配內存,並刪除它,而不實際插入值向量,他們 工作一樣快:
% cumulative self self total
time seconds seconds calls ms/call ms/call name
0.00 0.09 0.00 1 0.00 0.00 MyVector::MyVector(int)
0.00 0.09 0.00 1 0.00 0.00 MyVector::~MyVector()
我猜測是,當使用'new []'時,編譯器(在我的情況下是gcc)並沒有真正分配內存,只有當它需要它時(就像使用[]時一樣)。當它需要銷燬對象時,它有 取消分配在每次訪問期間分配的所有內存(使用[])。
我找不到任何文件 - 也許有一些我不知道。如果有人會分享他對這個問題的知識,我會很高興 。
編輯:我添加了我使用的代碼。 感謝迄今爲止所有的答案:
class MyVector
{
public:
MyVector(int size) { _data = new int[size]; };
~MyVector() { delete[] _data; } ;
int& operator[](int index) { return _data[i]; };
private:
int* _data;
int _size;
};
And the test:
int main() {
MyVector v(1000000);
for (int j = 0 ; j<20000 ; ++j) {
for (int i = 0; i<1000000; ++i) {
v[i]= i; //If i remove this line, destructor and constructor work just as fast
}
}
return 0;
}
你能顯示一些代碼嗎? – Default
'[]'不會插入或分配任何.... – Pubby
如果'調用1'意味着您在測試過程中只會調用一次這些函數,那麼我會質疑這些數字的價值。至少叫他們幾千次。 – Mat