Sobes.tech
Middle

What is dispatching?

sobes.tech AI

Answer from AI

Dispatching is the process of determining which specific method or function will be executed during program runtime.

In Swift, there are three main types of dispatch:

  1. Static (Static or Direct Dispatch): The fastest type. The compiler knows exactly which method will be called at compile time. There are no overheads for method lookup. Used for:

    • Structs.
    • Enums.
    • Methods in classes marked as final or private (if there is no @objc and no dynamic dispatch via Objective-C runtime).
    • Global and static functions.
    • Extensions.
  2. Table Dispatch: Used for classes. A virtual table (vtable) is created for each class, containing pointers to method implementations. When a method is called, the pointer is looked up in the table. There are slight overheads. Used for:

    • Instance methods of classes (class methods) not marked as final or private.
    • Computed properties.
    class Animal {
        func speak() { // Table Dispatch
            print("...")
        }
    }
    
    class Dog: Animal {
        override func speak() { // Overridden method, also Table Dispatch
            print("Woof")
        }
    }
    
  3. Dynamic Dispatch: The slowest. Method resolution occurs at runtime via the Objective-C runtime. Used for interacting with Objective-C. Has significant overheads. Used for:

    • Methods marked as @objc dynamic.
    • Properties marked as @objc dynamic.
    • Key-Value Observing (KVO).
    • Key-Value Coding (KVC).
    class SomeClass: NSObject {
        @objc dynamic func performAction() { // Dynamic Dispatch
            print("Performing action")
        }
    }
    

Summary table:

Type Speed Overheads Where used
Static High Low Struct, Enum, final/private class methods, extension
Table Medium Medium Instance methods of classes (not final/private)
Dynamic Low High @objc dynamic

Choosing the dispatch type is important for performance optimization. Swift defaults to the most efficient type that allows maintaining polymorphism flexibility where needed (using table dispatch for classes). Using final or private can help the compiler apply static dispatch.

What is dispatching? — iOS - sobes.tech