I need to improve the efficiency of my program and, using the profiler, have narrowed the problem down to 2 key areas, but I am having trouble coming up with ways to make the program run better.
Based on my profiler's report, it seems to be telling me that my if functions are inefficient. Whats a better way to achieve a better result?
Character* FindAttackTarget() const
{
float weakestHp = FLT_MAX;
Character* weakestEnemy = nullptr;
uint64_t weakestCharId = INT64_MAX;
//Only attack characters that are within attack range
auto& gameChars = m_pGame->m_gameCharacters;
for (size_t i = 0; i < gameChars.size(); ++i)
{
auto& c = gameChars[i];
if (Location.Dist(c.GetLocation()) <= AttackRange &&
c.HP > 0 &&
c.Team != Team)
{
//We want the weakest with the lowest ID number - this keeps consistent results when re-playing the same part of the game (eg. after a load game)
if (c.HP < weakestHp || (c.HP == weakestHp && c.ID < weakestCharId))
{
weakestEnemy = &gameChars[i];
weakestHp = c.HP;
weakestCharId = c.ID;
}
}
}
return weakestEnemy;
}
FindAttackTarget
implies it's finding a target to attack, which it does. But the name fails to deliver any of the relevant information that the function is retrieving the one with the lowest HP or the distance factor. One might improve this with something likeFindLowestHealthTarget
. \$\endgroup\$