I have a list defined like:
std::list<int *> m_ilist;
and I add ints to the list:
m_ilist.push_back (new int (x));
I want to destruct the vector and delete the memory that was allocated for each element.
Which one is better:
-
Doing a loop through the list, calling delete on each iterator. After this calling clear():
for (...) { delete *it; } m_ilist.clear (); -
Doing a loop but calling erase on the iterator:
for (...) { delete *it; m_ilist.erase (); }
Better would be defined as quicker / faster / less processing.
Thanks.
Benchmark it. More importantly, benchmark it in your particular application. There is no point in us testing a synthetic runtime of both versions, when your mileage will vary, depending on what you do afterwards.
The bottleneck is the nasty freeing and mallocing that goes on behind the curtains. Depending on the memory allocation pattern the remainder of your program exhibits, you will most likely get different results.
Having that said; The difference is most likely negligible, so my gut says go for the second and save one loop if in doubt.
Edit: Note that if you’re really concerned about speed, use an
std::vector<int>instead of anstd::list<int*>. The difference will be significantly larger than between the options you list.Edit 2: If you use an
std::vectormake sure to use variant 1 (withclearinstead of manyerases). In this case it does make a huge difference. If the elements are really huge (as opposed toint) you may want to actually put pointers (or smart pointers, for that matter) into the vector to minimise the copy overhead.