The memory usage of map in C ++ is studied. Many people say that erase and clear in map cannot release the memory. This statement is inaccurate after experiments over the past few days. The more accurate statement is that erase and clear in map cannot, "Release memory immediately. MAP has its own mechanism to recycle memory. After using erase and clear, if there is no special requirement, you can think that part of memory has been released. Map will not immediately release the memory for the deleted content, but will "reserve" the memory. If it does not use the reserved memory for a long time, it will be released.
After doing these experiments, P1 constantly fills the map and monitorsProgramMemory usage. Naturally, the memory is constantly increasing. P2 is to fill in the map with M data, one by one erase to 0, and then re-fill. As you can see, the memory in the filling process increases continuously, but the memory in the erase process is not continuously reduced. But after a while, it suddenly decreases by about 2 MB. The memory is increased to 200 MB. The P3 process is to first fill 100 m of data in the map, then erase drops the data of the even index (that is, delete 200 m), and then fill m, so that reciprocating. It is found that the memory usage starts to increase, and the memory remains unchanged when MB of data is deleted. Starting from the second round of filling, the memory remains unchanged until it is filled with more than MB, and the memory continues to increase.
From the above experiments, we can see that map has a more scientific memory reclaim mechanism. It can be considered that the space of clear and erase will be recycled at the appropriate time.