Swift & Concurrency (50 Qs)•Part 2: Concurrency, Actors & Advanced Architecture (11 - 24)
What are Method Dispatch mechanisms in Swift (Static vs Table vs Message Dispatch)?
senior LevelCode ExampleSystem Design
In Simple Words: How the CPU determines which executable memory address to jump to when calling a method:
- Static / Direct Dispatch (Fastest): Resolved at compile time. Inlined by compiler. Used for
structmethods,finalclass methods, and methods in class extensions. - Table / Witness Table Dispatch (Medium): Dynamic dispatch via a virtual function table (vtable for classes, witness table for protocols). Looks up pointer at runtime.
- Message Dispatch (Most Dynamic / Slowest): Pure Objective-C runtime lookup (
objc_msgSend). Can be swizzled at runtime. Used for@objc dynamicmethods.
text
Swift Dispatch Hierarchy:
Static Dispatch (Inlined, Compile-Time) ◄── struct / final class
Witness Table Dispatch (vtable) ◄── Class inheritance & Protocols
Message Dispatch (objc_msgSend) ◄── @objc dynamic & KVO