skip to content

A profiler flags dynamic_cast inside a C++ entity update loop; what makes the check costly, and what replaces it when RTTI is unavailable?

level: seniorimportance: should knowfreq 40%

answer

  1. a call into the C++ runtime
  2. walks the class hierarchy data
  3. ask the object, not its type
  4. closed sets fit a variant

basics

~20 s

A checked downcast is usually a runtime-library call that walks the dynamic type's inheritance description, slower with deep or multiple inheritance. Replace it with a virtual function, a type tag, std::variant, or typed pointers stored once at spawn time.

solid answer

~50 s

On Itanium-ABI toolchains a checked `dynamic_cast` compiles to a call to the runtime function `__dynamic_cast`, which typically starts from the object's `std::type_info` and searches the class's base-class description for the target; the compiler does not reduce it to a compare, and its work grows with hierarchy depth, multiple and virtual inheritance. Apple clang 21 at `-O2` still emitted that call for a `final` target. An exact-type test, `typeid(*e) == typeid(Player)`, is usually cheaper but answers a different question. The durable fixes remove the question: a **virtual function** such as `on_reward()` lets each class react; a **type tag** in the base allows an unchecked cast after the tag is checked; **`std::variant`** with `std::get_if` or `std::visit` suits a closed set of types held by value; and **caching typed pointers** when an entity spawns hoists the cast out of the frame. All of these also work in builds with RTTI disabled.

code

cpp · 32 lines
cpp
#include <iostream>
#include <variant>
#include <vector>

// Before: for each Entity*, if (auto* p = dynamic_cast<Player*>(e)) p->score += 10;

// Option 1: ask the object, not its type - a virtual hook.
struct Entity {
    virtual ~Entity() = default;
    virtual void on_reward(int) {}          // default: ignore
};
struct Player : Entity {
    int score = 0;
    void on_reward(int pts) override { score += pts; }
};

// Option 2: a closed set of types held by value in std::variant.
struct PlayerData { int score = 0; };
struct MonsterData { int hp = 50; };
using Thing = std::variant<PlayerData, MonsterData>;

int main() {
    Player hero;
    Entity* e = &hero;
    e->on_reward(10);
    std::cout << hero.score << '\n';

    std::vector<Thing> world{PlayerData{}, MonsterData{}};
    for (Thing& t : world)
        if (auto* p = std::get_if<PlayerData>(&t)) p->score += 10;
    std::cout << std::get<PlayerData>(world[0]).score << '\n';
}

go deeper

for a junior

Know that dynamic_cast does real work at run time, unlike an upcast, and that virtual functions are the usual way to avoid it.

for a middle

Explain what the runtime check searches, why exact-type typeid differs from is-a, and how a variant or a type tag replaces the cast.

for a senior

Read the profile and the generated code, pick the replacement that fits the hierarchy, and hoist repeated casts out of per-frame loops.

for a principal

Decide which dispatch technique a subsystem standardises on, weighing open extension against closed sets and the cost of RTTI-dependent code.

## What a checked downcast compiles to A `dynamic_cast` that is a plain upcast costs nothing more than a pointer adjustment. A **checked** one, a downcast or cross-cast, has to discover the object's dynamic type and search its inheritance graph. On toolchains that follow the Itanium C++ ABI (GCC and Clang on most platforms), the compiler emits a call to a runtime-library function, `__dynamic_cast`, passing the source and target `std::type_info` objects. Compiling a loop of `dynamic_cast<Player*>` with Apple clang 21 at `-O2` produced exactly that call, even with `Player` declared `final`. What the runtime does is the implementation's choice, but typical implementations: - read the object's virtual table to find the most derived type's `type_info` and the offset to the complete object; - walk that type's description of its base classes, recursively, looking for the target; - check public access and uniqueness, which takes more work when multiple or virtual inheritance is involved; - on platforms where RTTI objects may be duplicated across shared libraries, fall back to comparing type **names**. libc++ documents a "NonUnique" mode that compares names with `strcmp` when addresses differ, and an Apple arm64 mode that compares addresses when both objects are marked unique and names when both are marked non-unique. None of it is enormous, but it is a call, several dependent loads and branches per entity per frame, and it blocks the optimizer from seeing through the loop. ## The exact-type shortcut `typeid(*e) == typeid(Player)` compares two `type_info` objects. In libc++'s Unique configuration that is a pointer comparison; on Apple arm64, the compiled code compared addresses and fell back to `strcmp`. It is often cheaper than `__dynamic_cast`, but it answers **"is this exactly a Player?"**, so a `Boss` derived from `Player` fails the test. Use it only when exact type is genuinely the question. ## Alternatives that remove the question | Technique | Fits when | Needs RTTI? | |---|---|---| | virtual function on the base | each type reacts differently to the same event | no | | type tag in the base + unchecked cast | a fixed, known set of derived classes | no | | `std::variant` + `std::get_if` / `std::visit` | a closed set held by value | no | | typed pointers cached at spawn | the same lookup repeats every frame | no | 1. **Ask the object, not its type.** Replace `if (auto* p = dynamic_cast<Player*>(e)) p->score += 10;` with a virtual `on_reward(int)` that does nothing by default and adds to the score in `Player`. One indirect call replaces a runtime search, and new entity types opt in without editing the loop. 2. **Type tags.** Store an `enum class Kind` in `Entity`, set by each constructor. After checking `e->kind() == Kind::Player`, an unchecked conversion is safe by construction. It is fast and explicit, but every new class must set its tag correctly, and nothing in the language enforces that. 3. **`std::variant`.** When the set of types is closed, store `std::variant<PlayerData, MonsterData>` by value. `std::get_if<PlayerData>(&v)` is a check of a stored index; `std::visit` dispatches over all alternatives with compile-time exhaustiveness. It changes the data model, so it suits new subsystems more than retrofits. 4. **Cache once.** If the update loop only ever needs players, keep a separate `std::vector<Player*>` filled when entities spawn or despawn. The cast, if any, happens once per entity lifetime, not once per frame. ## Builds without RTTI Some codebases disable RTTI to save binary size; how and why is covered with restricted builds. In such builds Clang rejects a checked `dynamic_cast` (`use of dynamic_cast requires -frtti`) and `typeid` (`use of typeid requires -frtti`). Every technique in the table works there; the code example compiles and runs the same with RTTI on or off. ## Measuring before and after Profile with the real entity mix: the cost depends on how often the cast fails, the hierarchy's shape and the platform's RTTI configuration. A micro-benchmark of one cast in isolation tends to mislead, because the cost that matters is the loop's, including cache misses on the objects themselves.

  • Why can declaring Player final not guarantee that a C++ compiler turns dynamic_cast<Player*> into a cheap compare?
    `final` tells the compiler no class derives from `Player`, so a successful cast must find an object whose dynamic type is exactly `Player`; in principle that is one type-identity check. Whether the compiler uses it depends on the toolchain and on whether type identity is a pointer compare on that platform. Apple clang 21 at `-O2` on arm64 still emitted a call to `__dynamic_cast`, so measure rather than assume.
  • What does a type tag in a C++ base class trade away compared with dynamic_cast?
    It trades the language's check for a convention. The tag lookup is a load and a compare, and it works without RTTI, but the compiler does not verify that each derived class sets the right tag, that the tag matches the class, or that subclasses of `Player` are handled. A wrong tag turns the following unchecked cast into undefined behaviour, so tags suit small, closed hierarchies with a test that covers every class.

  • dynamic_cast is resolved at compile time, so it costs nothing at run time.
  • typeid(*e) == typeid(Player) answers the same question as a Player downcast.
  • Marking the target class final always makes dynamic_cast a single compare.
  • Without RTTI there is no safe way to tell entity types apart.
  • std::variant needs RTTI to know which alternative it holds.