I added a large number of elements and then deleted them all in a boost::unordered_map.
Then I saw the memory held by this program is 198MB (greater than (64+4)*2M) and the unordered_map size is 0.
I then test a vector, and there is no such problem. Why?
#include <iostream>
#include <boost/unordered_map.hpp>
template <int N>
struct big_struct {
char c[N];
};
int main(void) {
typedef big_struct<64> data_type;
typedef boost::unordered_map<int, data_type*> map_type;
map_type m;
for (int i = 0; i < 2000 * 1000; i++) {
m.insert(std::make_pair(i, new data_type));
}
for (map_type::iterator it = m.begin(); it != m.end();) {
delete it->second;
it = m.erase(it);
}
std::cout << "finish, map size " << m.size() << std::endl;
pause();
return 0;
}
The language runtime holds on to the allocated memory, assuming that you might want to use it again. Returning millions of small blocks to the OS would take quite some time, and make your program run slower.
If you have a very large vector, that is still only a single memory block. Some compilers consider returning this kind of memory when it is not needed anymore. Returning one large block is considerably more efficient than a million small blocks.