Delegates do have some performance overhead compared to direct function calls. Let's break down the costs and examine when they matter.
A direct function call is typically compiled into a single CPUÂ instruction:
class Player {
public:
void TakeDamage(int Damage) {
UpdateHealthBar(Health - Damage);
}
private:
void UpdateHealthBar(int NewHealth) {
std::cout << "Health: " << NewHealth << '\n';
}
int Health{100};
};
A delegate using std::function
 involves:
class Player {
public:
using DamageDelegate = std::function<
void(int NewHealth)>;
void SetDelegate(DamageDelegate D) {
OnDamage = D;
}
void TakeDamage(int Damage) {
if (OnDamage) OnDamage(Health - Damage);
}
private:
DamageDelegate OnDamage;
int Health{100};
};
For most games, this overhead is negligible. Consider:
However, if you're calling delegates thousands of times per frame, you might want to consider alternatives:
The key is to profile your specific use case. Don't optimize prematurely - start with the cleaner delegate-based design, and only optimize if profiling shows it's necessary.
Answers to questions are automatically generated and may not have been reviewed.
An overview of the options we have for building flexible notification systems between game components