Dynamic dispatch

On this page 7

Dynamic dispatch is the mechanism that selects which implementation of a method to run at runtime, based on the actual type of the receiving object rather than the declared type of the variable that refers to it. In object-oriented programming, it is the engine behind subtype polymorphism: code written against a base class or interface can call a method and automatically reach the overriding version in whatever subclass the object really belongs to.

The opposite approach, static dispatch, resolves the call at compile time from the declared type. Most languages combine both, and understanding where each applies explains a great deal about performance, extensibility and subtle bugs in object-oriented code.

How dynamic dispatch resolves a method call

A dynamically dispatched call is resolved in two steps: the compiler checks that the method exists on the declared type, and the runtime then looks up the concrete implementation on the object itself. When code calls shape.area() on a variable declared as Shape, the program inspects the object, finds that it is a Circle, and executes Circle.area.

In statically typed languages such as C++, Java and C#, the usual implementation is a virtual method table, or vtable. Each class has one table of function pointers, one slot per virtual method, and every object carries a hidden vtable pointer set by the constructor. A call loads that pointer, indexes the correct slot and jumps to the address it finds, which costs one or two extra memory loads and an indirect branch.

Dynamically typed languages such as Python, Ruby and Smalltalk use name-based lookup instead: the runtime searches the class and its ancestors for a method with the requested name, following the method resolution order. Because this search is expensive, interpreters and JIT compilers cache results in inline caches keyed by the receiver’s class.

The following table summarizes the main implementation strategies and where each is typically found.

StrategyHow the target is foundTypical languages
Vtable lookupFixed slot index in a per-class tableC++, Java, C#
Interface table (itable)Search or hash per implemented interfaceJava, C#, Go
Dictionary lookupMethod name searched along the class chainPython, Ruby
Message send with cacheSelector lookup cached per call siteSmalltalk, Objective-C
Prototype chainProperty search through linked objectsJavaScript
Common implementation strategies for dynamic dispatch

Single, double and multiple dispatch

Mainstream object-oriented languages use single dispatch: only the runtime type of one argument, the receiver, decides the implementation. The types of the other arguments are considered only at compile time, through method overloading, which is a static mechanism despite its similar appearance.

Multiple dispatch, also called multimethods, selects the implementation from the runtime types of all arguments. Common Lisp’s CLOS and Julia build their whole design on it. Languages without native support emulate the two-argument case with double dispatch, most famously through the Visitor pattern, where an element calls back into the visitor with its own concrete type.

The table below contrasts the dispatch forms by what determines the chosen method.

Dispatch formDecided byResolved atExample
Static dispatchDeclared typesCompile timeNon-virtual C++ method
Single dispatchReceiver’s runtime typeRuntimeJava instance method
Double dispatchTwo runtime types via callbackRuntime, two callsVisitor pattern
Multiple dispatchAll arguments’ runtime typesRuntimeJulia function methods
Dispatch forms compared

Language defaults and how to control dispatch

Languages differ in whether methods are dynamically dispatched by default. In Java, every non-static, non-private, non-final instance method is virtual. In C++ and C#, a method is dispatched dynamically only when marked virtual, and a derived class must use override in C# to replace it. This difference reflects a design choice between openness to extension and predictable performance.

Several keywords let developers opt out of dynamic dispatch where it adds cost without benefit. Marking a class or method final in Java or C++, or sealed in C#, tells the compiler that no further overriding is possible, which enables direct calls and inlining.

LanguageDefault for instance methodsOpt-in or opt-out
JavaDynamicfinal disables overriding
C++Staticvirtual enables, final closes
C#Staticvirtual and override, sealed closes
PythonDynamicNo opt-out; all lookup is runtime
RustStatic via genericsdyn Trait enables trait objects
Dispatch defaults in selected languages

Rust and Go illustrate a newer approach: dispatch is attached to trait objects or interface values rather than to class hierarchies. A Rust dyn Trait reference is a fat pointer holding both the data address and a vtable address, so the dispatch cost is paid only where the programmer explicitly asks for it.

Performance costs and compiler optimizations

The raw cost of a virtual call is small, typically a few nanoseconds or less, but the larger price is indirect: an unknown target prevents inlining, which blocks constant propagation, loop optimizations and vectorization. In tight loops over millions of objects, this can matter more than the call overhead itself.

Compilers recover much of the cost through devirtualization. When analysis proves that only one implementation can be reached, the call becomes a direct one. JIT compilers such as the HotSpot JVM go further with speculative devirtualization: they observe which classes actually appear at a call site and inline the common case behind a cheap type guard.

OptimizationConditionEffect
Class hierarchy analysisOnly one override is loadedDirect call and inlining
Monomorphic inline cacheOne receiver class at the call siteLookup replaced by a type check
Polymorphic inline cacheTwo to a few receiver classesShort chain of type checks
Megamorphic fallbackMany receiver classesFull lookup on every call
Final or sealed typesOverriding is forbiddenStatic call at compile time
Optimizations that reduce dispatch overhead

Common pitfalls with dynamic dispatch

Most dispatch bugs arise when developers assume a call is dynamic when it is actually static, or the reverse. The following mistakes appear repeatedly in code reviews.

  • Calling virtual methods in constructors: in C++ the call reaches the base version because the derived part does not yet exist; in Java it reaches the override before the subclass fields are initialized.
  • Missing virtual destructor: deleting a derived object through a base pointer in C++ without a virtual destructor is undefined behavior.
  • Confusing overloading with overriding: an overload chosen by declared argument types does not change when the runtime type changes.
  • Accidental hiding: a method with a slightly different signature creates a new method instead of an override; the override keyword or @Override annotation catches this at compile time.
  • Object slicing: copying a derived object into a base-class value in C++ discards the derived part, so later calls dispatch to the base.

In simple terms

Dynamic dispatch means the program decides at the last moment which version of an action to perform, based on what the object really is. Imagine telling a group of animals to speak. You give the same instruction to all of them, yet the dog barks and the cat meows, because each one answers in its own way.

The person giving the instruction does not need a list of every animal. New kinds of animals can join later and still respond correctly. That is the main benefit: general code keeps working as specific types are added.

A practical example

A team building a vector drawing application stores every element on the canvas in one list of type Shape. Rectangles, ellipses, paths and text boxes each override draw and hitTest. The rendering loop simply calls draw on each element, and dynamic dispatch routes every call to the correct subclass, so adding a new star tool requires only a new class and no change to the renderer.

Profiling later shows that a document with 200,000 small rectangles redraws slowly. The call site is effectively monomorphic, and after the team marks the leaf classes final and groups elements by type, the JIT inlines the drawing code and frame time drops noticeably. The design keeps its flexibility while the hot path behaves almost like direct static calls.