Tuesday, January 23, 2007

Shrink to fit

I have found quite a number of people wondering if the vector object releases memory once it goes out of scope or is cleared. Some even start assuming it to be a flaw with their STL vector implementation.

Well... it's not that and it certainly isn't a flaw. It just indicates that the runtime does not immediately release all the memory not being used by a cleared vector to the operating system heap manager.

Not only that, sometimes after a call to clear, you may note that the size becomes 0 but the capacity remains the same. That means the vector object is still keeping a huge array internally. This sometimes proves efficient in that the runtime does not always need to go and ask the heap manager to provide blocks from the free store (which is considered to be an expensive operation).

There is a technique though, with which you can do the best about it. It is famed by the name shrink-to-fit. To know more about this technique, please take a look at the following FAQ - http://www.codeguru.com/forum/showthread.php?t=405839

Nice one... isn't it? Have fun! Cheers.

No comments: