I have a vector of pointers that I really need to make sure the used memory is free before proceeding with other tasks in the program. I do not want to rely on operating system to manage the calls to
#define NUM_ELEMENTS 1000000
double PCFreq = 0.0;
__int64 CounterStart = 0;
std::cout << "QueryPerformanceFrequency failed!\r\n";
PCFreq = double(li.QuadPart) / 1000.0;
CounterStart = li.QuadPart;
return double(li.QuadPart - CounterStart) / PCFreq;
/***** CREATE VECTOR **********/
std::cout << "Generating " << NUM_ELEMENTS
<< " elements." << std::endl;
std::vector<int *>* vec = new std::vector<int*>;
for (size_t i = 0; i < NUM_ELEMENTS; i++)
std::cout << vec->size() << " Have been generated in "
<< GetCounter() << "ms" << std::endl;
std::cout << "Destroying the vector..." << std::endl;
/***** DELETE VECTOR **********/
delete vec->back(), vec->pop_back();
std::cout << "It took " << GetCounter() << "ms to empty the vector!\r\n"
<< "Press ENTER to exit." << std::endl;
//wait for key to exit
Generating 1000000 elements.
1000000 Have been generated in 1077.96ms
Destroying the vector...
It took 16834.9ms to empty the vector!
Press ENTER to exit.
The improvement is trivial: use
vector<int> instead of
vector<int*>, since you're storing only one element per pointer.
If your data is larger and you really need to store pointers, use
boost::ptr_vector. This isn't 1980 anymore, you can use RAII.
As for slow cleanup, it's probably because your runtime has a lot of entries in their small allocation structures and has to walk them all to find the correct one.
If you need to have a vector of pointers but need faster deallocation, try keeping the vector of pointers as it is and keep the actual data in
deque-like container (a
array<data_t,32>, perhaps? You'd have to do the index-keeping yourself, but it'd speed up deletion if that's the bottleneck).