bartek szurgot <ba...@no.spam> writes:
>On 06/03/2012 07:34 PM, sukhmeet wrote:
>> Hi,
>> I wrote a program in which I define a vector of some class objects.
>> Initially the vector has size and capacity both set to 0.
>> The moment I add an element to the vector the size is 1 and the capacity
>> jumps to 32 elements.
>> This is causing a huge overhead on my program since I need to use many such
>> vectors to load reference data with max capacity of 10 elements.
>> Is there a way to set the max vector capacity or resize it to fit the
>> vector to its size at any point of time.
>
>hi,
>
>the best way is to use vector::reserve(). if it is not an option, C++11
>has vector::shrink_to_fit() method. it is very convenient, though it is
>not guaranteed to resize a container; it does so on gcc-4.[567], so
>check your compiler.
>
It's not really up to the compiler. It's up to the run-time library and
the operating system to reduce the physical memory footprint of an application. Once
memory has been allocated to the heap, it is quite difficult to
give it back to the OS (unix heaps allocated with sbrk(2) can only return
memory to the OS if the unused memory is (a) contiguous and (b) at the
end of the heap). If using mmap(2) to allocate heap, the amount returned
must be page-aligned and multiples of a page and must not contain other
allocations (which is common in a heap implementations).
If the application doesn't access whole pages in the heap, and the system is
under memory pressure, the OS will move the unaccessed pages to backing storage
and allow another application to use the physical memory pages, but this
is independent of any standard library interface such as vector::shrink_to_fit.
At best, ::shrink_to_fit is a hint to the library which may result in a
spurious copy as it mallocs a smaller chunk, copies it, and free's the
larger (which still remains as part of the process heap).
If std::vector uses operator::new to allocate, then all other callers
of new will get elements from the same heap, which will make it difficult
to find sufficient contiguous regions of heap to return any storage to the system.
Far better not to allocate too much in the first place, or to control large
allocations by explicitly using ::mmap(2) (or the windows equivalent) in a
customer operator::new.
scott