2013-06-12 96 views
1

的快速分配我是一個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秒。我做了什麼明顯錯誤?

+0

是你編譯優化? –

+0

你是如何計時的? –

+1

您可能會發現這對於池分配器非常有用,因爲每個節點的大小相同,並且在刪除列表時,您可以告訴分配器立即刪除整個內存塊(不需要循環)。 –

回答

3

這可能是運行時間庫如何取消分配內存的工件。在分配過程中,爲每個節點項目查找塊可能只是執行主池的一些操作,並將其分成兩部分並返回小部分以供程序使用。釋放該塊可能包括走一個空閒列表,看看這些小分配是否可以組合成更大的空閒塊。

+0

這似乎是最合理的答案,所以我將其標記爲正確。 –

0

嘗試運行在發佈模式而不是調試。

在調試模式下,釋放塊時,運行時會執行大量的理智檢查,以確保不會覆蓋您不擁有的內存,並且還會擦除釋放的內存內容。在Release中,所有的開銷都消失了。

(請注意,我這裏假設你正在使用開發工作室。其他平臺有使內存檢查不同的規則,但你的問題聽起來非常相似,我的開發工作室在調試模式下的經驗。)