1.11 · Static vs dynamic dispatch

Every call has to be resolved. The question is when — compile time or runtime — and that single answer explains performance, overriding, and the “my method never ran” bug.

Mental model. Static = the compiler already knows. Dynamic = something is only known at runtime: a subclass, an existential, or an Objective-C receiver.

Static vs dynamic

How a call finds its implementation.

  1. Static vs dynamic dispatch in Swift? 1.11.1 · L2
    Static — the compiler knows the exact implementation: structs, enums, generics after specialization, final classes, and protocol extension methods that are not…
  2. Why does final (and whole-module optimization) help performance? 1.11.2 · L3
    final tells the compiler no subclass can override the method, so it can devirtualize the call into a direct one — and then inline it. Whole-module optimization…

The protocol extension trap

Same call, different method, depending on the static type.

  1. You added a method in a protocol extension and overrode it on a concrete type, but calling through any P does not hit your override. Why? 1.11.3 · L5
    Because the method is not a protocol requirement. Only requirements get a slot in the witness table. A method that exists only in an extension is a plain…

More in Swift language