Original Post
Consider this code:
#include <iostream>
#include <list>
#include <vector>
int main()
{
std::list<int> nums;
for (int i = 0; i < 1000; ++i)
{
nums.clear();
for (int j = 0; j < 5000; ++j)
{
nums.push_back(j);
}
}
}
Executing it results in a noticeable pause (about 2-3 seconds). Now, replace std::list with std::vector. No other changes. The resulting executable executes and finishes instantly. I noticed this while messing around in school with Code::Blocks and GCC 4.4 on my USB, and I just confirmed it with MSVC 2008 Pro. Call me stupid, but I cannot grasp what is going on here. I thought std::list::push_back was O(1)? In fact, I rolled my own implementation just to be sure:
// custom test list
namespace detail
{
template <typename T>
class list
{
private:
struct node
{
T val;
node(const T &val): val(val), next(NULL) {}
node *next;
};
node *_head, *_tail;
public:
list(): _head(NULL), _tail(NULL) {}
~list() { clear(); }
void push_back(const T &val)
{
node *n = new node(val);
if (!_tail)
_head = _tail = n;
else
{
_tail->next = n;
_tail = n;
}
}
void clear()
{
node *n = _head;
while (n)
{
node *old = n;
n = n->next;
delete old;
}
_head = _tail = NULL;
}
};
}
Once again, same slowness... (removing the call to clear() every iteration doesn't change anything at all regarding the speed) I'm a bit baffled. Is it because std::vector::push_back is essentially O(1) if capacity() > size()? Even so, list::push_back is always O(1), it's essentially an allocation and an assignment - is it the memory allocation that is tripping it up?