I have a class Test
which contains one member variable vector<MyCls> m_vObj
and two member functions clear_vec
and func
. Please see the following code.
The func
has a for
loop, and each time it will push_back
some instances into m_vObj
, do some computation, and output the computation results. After that, I call clear_vec
to clear the m_vObj
vector, and prepare for the next loop.
Currently, I swap
the m_vObj
with an empty vector according to this suggestion. But I find the member function clear_vec
is time-consuming especially for the swap
(line 1).
As far as I understand, I just need to clear all elements in m_vObj
and I do not need to free the memory. However, clear_vec
in the for
loop will frequently allocate memory and free memory. If I comment line 1 and just keep line 2, I can clear the vector but do not re-allocate memory frequently. Is it safe and will it be more efficient?
class Test {
private:
vector<MyCls> m_vObj;
public:
void clear_vec() {
vector<MyCls>().swap(m_vObj); // line 1
m_vObj.clear(); // line 2
}
void func() {
for (int i = 0; i < 100; ++i) {
// push_back some instances into m_vObj
// do some computations with m_vObj
// output computation results
clear_vec();
}
}
};