Vector clear vs. resize
I read on the Internet that if you are clearing a std::vector
repetitively (in a tight loop), it might be better to use resize开发者_运维知识库(0)
instead of clear()
, as it may be faster. I am not sure about this. Does anyone have a definitive answer to this?
I assume you mean resize(0)
instead of setsize
, and calling that instead of clear()
, and that you're talking about std::vector
. IIRC a recent answer discussed this (can't find the link), and on modern STL implementations, clear()
is likely identical to resize(0)
.
Previously clearing a vector might have freed all its memory (ie. its capacity also falls to zero), causing reallocations when you start adding elements again, in contrast to resize(0)
keeping the capacity so there are fewer reallocations. However, I think in modern STL libraries there is no difference. If you're using an old STL implementation, or you're just paranoid, resize(0)
might be faster.
Looking at Dinkumware STL source, both effectively call erase(begin(), end());
clear()
is slightly more efficient, unsurprisingly., as it has just the one case to deal with. but I wouldn't expect it's measurable.
There appears to be a difference between clear and resize(0) when the vector contains objects of a class that does not have a default constructor. For example, the following code will compile:
#include <vector>
class A {
private:
int x,y;
public:
A(int x,int y) :x(x), y(y) {}
};
int main() {
std::vector <A> aa;
aa.clear();
}
But if you substitute the aa.clear()
by aa.resize(0)
, you get compilation error:
error: no matching function for call to 'A::A()'
This sound implementation specific, and is a job for you, your library and a profiler. But as I see it, I cannot see why resize(0) should be quicker when both will in effect have to call erase(begin(),end()).
精彩评论