N
Niklas Norrthon
In said:No rule without exceptions...
Last week I used malloc in C++ for the first time in the 15 years I've
been playing with the language... I had a buffer which I needed to
shrink every once in a while, so I saved lots of CPU cycles switching
from new[] and delete[] to malloc, realloc and free.
Someone replied, suggesting using vector<>::resize(). But resize just
calls erase which causes destructors of contained objects to be called,
but it does not release any memory held by the vector. My contained
objects were unsigned chars, so destructors or not was not an issue.
Then the suggestion came to use the vector<>::swap() trick, to
return any memory not used. At this point the people over next
door had had enough (and who can blame them?).
So now I move over here...
My problem was:
A large array (a megabyte or two) of unsigned char gets populated by
a library function. Then the data in the array gets processed, and
after a chunk is used it is not needed anymore, so there is no need
to hold on to that memory any longer if the chunk not needed is at the
end of the array (which happens about 25% of the time).
My first attemt was to use a vector, and the swap trick to return
unused memory. There were two problems with this approach: While
swapping twice the memory is allocated, and the entire vector had
to be copied every time.
The solution was of course to switch to malloc and realloc instead.
Now it is functioning and fast. The calls to the C memory management
functions take place deep inside a class, so no other program logic
was affected at all. Only difference is a much smaller memory foot
print, and a faster program.
/Niklas Norrthon