的快速分配我是一個C++初學者和我碰到一個令人沮喪的問題 -鏈表和緩慢釋放
我有這個模板LinkedList的實現:
template <typename U>
class LinkedList : std::iterator<std::input_iterator_tag, U> {
public:
struct Node {
friend LinkedList;
U content;
Node* getNext() { return next; };
private:
Node* next;
Node* prev;
};
LinkedList() : head(NULL), tail(NULL) { };
~LinkedList() {
Node * current = tail;
while(current != NULL) {
Node* temp = current;
current = current->prev;
delete temp;
}
};
Node* getHead() { return head; }
Node* getTail() { return tail; }
bool append(U content) {
Node* node = new Node();
if(node == NULL) return false;
node->content = content;
if(tail == NULL) {
tail = head = node;
} else {
tail->next = node;
node->prev = tail;
tail = node;
}
return true;
};
bool remove(U* cont) {
if(tail == NULL) return false;
if(cont != NULL) *cont = tail->content;
Node *temp = tail;
if(tail == head) {
tail = NULL;
head = NULL;
} else tail = temp->prev;
delete temp;
return true;
};
private:
Node *head, *tail;
};
我運行下面的代碼反對它:
char c1, c2;
cout << "start allocation" << endl;
LinkedList<int>* list = new LinkedList<int>();
for(ULONGLONG i = 0; i < 1e5; i++) {
list->append(0);
}
cout << "allocation complete" << endl;
cin >> c1;
cout << "start deleting" << endl;
delete list;
cout << "done deleting" << endl;
cin >> c2;
cout << c2 << endl; // don't optimize read key away
因此它分配100,000個int節點,然後它刪除它們全部。爲所有節點分配空間幾乎是瞬間的,而刪除它們需要大約10秒。我做了什麼明顯錯誤?
是你編譯優化? –
你是如何計時的? –
您可能會發現這對於池分配器非常有用,因爲每個節點的大小相同,並且在刪除列表時,您可以告訴分配器立即刪除整個內存塊(不需要循環)。 –