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 read on the Internet that if you are clearing a std::vector repetitively (in
Share
I assume you mean
resize(0)instead ofsetsize, and calling that instead ofclear(), and that you’re talking aboutstd::vector. IIRC a recent answer discussed this (can’t find the link), and on modern STL implementations,clear()is likely identical toresize(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.