Codechange: Replace GroupStatistics' num_engines with std::map. (#11849)

This removes manual memory management with calloc/free calls, and prevents potentially large arrays being allocated for each group.

(cherry picked from commit 8797cc7ef2)
This commit is contained in:
Peter Nelson
2024-01-21 14:09:44 +00:00
committed by Jonathan G Rennison
parent 17934bcc90
commit be147651d4
4 changed files with 22 additions and 21 deletions

View File

@@ -35,16 +35,6 @@ GroupID _new_group_id;
GroupPool _group_pool("Group");
INSTANTIATE_POOL_METHODS(Group)
GroupStatistics::GroupStatistics()
{
this->num_engines = CallocT<uint16_t>(Engine::GetPoolSize());
}
GroupStatistics::~GroupStatistics()
{
free(this->num_engines);
}
/**
* Clear all caches.
*/
@@ -55,9 +45,20 @@ void GroupStatistics::Clear()
this->num_vehicle_min_age = 0;
this->profit_last_year_min_age = 0;
/* This is also called when NewGRF change. So the number of engines might have changed. Reallocate. */
free(this->num_engines);
this->num_engines = CallocT<uint16_t>(Engine::GetPoolSize());
/* This is also called when NewGRF change. So the number of engines might have changed. Reset. */
this->num_engines.clear();
}
/**
* Get number of vehicles of a specific engine ID.
* @param engine Engine ID.
* @returns number of vehicles of this engine ID.
*/
uint16_t GroupStatistics::GetNumEngines(EngineID engine) const
{
auto found = this->num_engines.find(engine);
if (found != std::end(this->num_engines)) return found->second;
return 0;
}
/**
@@ -1032,9 +1033,9 @@ uint GetGroupNumEngines(CompanyID company, GroupID id_g, EngineID id_e)
uint count = 0;
const Engine *e = Engine::Get(id_e);
IterateDescendantsOfGroup(id_g, [&](Group *g) {
count += GroupStatistics::Get(company, g->index, e->type).num_engines[id_e];
count += GroupStatistics::Get(company, g->index, e->type).GetNumEngines(id_e);
});
return count + GroupStatistics::Get(company, id_g, e->type).num_engines[id_e];
return count + GroupStatistics::Get(company, id_g, e->type).GetNumEngines(id_e);
}
/**