Delegates and the Observer Pattern

Delegate Performance Impact

How does the performance of delegates compare to direct function calls?

Abstract art representing programming

Delegates do have some performance overhead compared to direct function calls. Let's break down the costs and examine when they matter.

Direct Function Calls

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};
};

Delegate Calls

A delegate using std::function involves:

  • A virtual function call (typically 2-3 instructions)
  • Possible heap allocation during delegate setup
  • Small memory overhead for storing the delegate
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};
};

Performance Impact

For most games, this overhead is negligible. Consider:

  • Modern CPUs execute billions of instructions per second
  • Delegate calls typically happen in response to events (damage, collecting items, etc.) rather than every frame
  • The flexibility benefits often outweigh the small performance cost

However, if you're calling delegates thousands of times per frame, you might want to consider alternatives:

  • Raw function pointers (less overhead but less flexible)
  • Direct virtual function calls
  • Compile-time polymorphism using templates

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.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 53 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved