Middle
What is the structure of dispatching?
sobes.tech AI
Answer from AI
There are three main types of method dispatching in Swift:
-
Direct Dispatch: The fastest. The compiler knows exactly which method to call at compile time. Used by default for structs, classes with final methods, private methods.
struct MyStruct { func directMethod() { // Direct dispatch print("Direct") } } -
Table Dispatch: Used for class methods (not final). Each class has a virtual method table (vtable), where each method has a unique index. The compiler accesses the vtable at runtime to find the correct implementation. Allows polymorphism.
class MyClass { func tableMethod() { // Table dispatch print("Table") } } class MySubClass: MyClass { override func tableMethod() { // Overridden method also uses the table print("Table override") } } -
Message Dispatch: The most flexible but slowest. Used for objc methods (marked
@objc dynamic). The Objective-C system looks up the method implementation by its name (selector) at runtime.@objc class MyObjcClass: NSObject { @objc dynamic func messageMethod() { // Message dispatch (for ObjC, dynamic) print("Message") } }
| Dispatch Type | Speed | Flexibility (polymorphism, dynamism) | Default application |
|---|---|---|---|
| Direct | Fast | Low | Structs, final classes/methods, private |
| Table | Medium | Medium | Class methods |
| Message | Slow | High | @objc dynamic methods (Objective-C) |