Problem
My current project implements a pool of objects to avoid constant memory allocation and de-allocation for speed purposes, the object pool is a std::vector<object>
and I would like to implement a form of garbage collection to reduce memory usage and increase performance. Every loop the program iterates over the entire vector and if the object is active, executes the update function, this means that if my vector is full of inactive objects, I will be wasting a lot of time iterating over them and also memory storing them. I cannot clean the vector every frame as this would crush performance.
Current attempt
My current attempt at implementing this has been to measure the update time, and use a pre-defined function to determine whether or not we are spending too much time on the update, for the amount of objects currently active, if we are, I clean the vector once to allow the speed to return to normal.
#include <chrono>
void updateObjects()
{
auto begin = std::chrono::high_resolution_clock::now();
//update all objects
for(auto o : objectVec)
{
//only update active objects
if(o.m_alive)
{
o.update();
}
}
//end time of update
auto end = std::chrono::high_resolution_clock::now();
//calculate time taken vs estimated time
auto elapsed = (end-begin).count();
//Estimate is based on performance testing
long estimate = 25*m_particleCount+650000;
//If we have no active objects,
//but are wasting memory on storing them, we clean up
//If the update takes longer than it should, we clean up
if(((objectCount <= 0) && (objectVec.size() > 0)) || (elapsed > estimate))
{
cleanVec(); //remove inactive objects
}
}
This solution works well on my pc, however I am having issues with it on other computers as the time taken for the update to complete varies due to different CPU speeds, and my pre-defined function then doesn't work as it is based off of incorrect data. I am wondering if there is another measurement I can use for this calculation? Is there a way I can measure the pure amount of instructions executed, as this would be the same across computers, some would simply execute them faster? Any other suggestions are welcome, thank you!
Edit
The object pool can be as large as 100,000 objects, typical usage will range from 3000 to the maximum. My function for cleaning is:
objectVec.erase(std::remove_if(objectVec.begin(),
objectVec.end(),
[](const object& o) {return !(o->m_alive);}),
objectVec.end());