Sobes.tech
Middle+

How to write code so that it works quickly in terms of dynamic dispatch?

sobes.tech AI

Answer from AI

Use struct and enum instead of class where possible. Value types by default do not use dynamic dispatch.

Apply final to classes and methods to prevent inheritance and overriding, allowing the compiler to perform direct dispatch.

final class MyFinalClass { // Class cannot be inherited
    final func myFinalMethod() { // Method cannot be overridden
        // ...
    }
}

Use protocols with only static or final method/property requirements, or with generics that can be specialized at compile time.

protocol MyProtocol {
    static func staticMethod()
}

Use private and fileprivate for methods and properties inside classes/structs/enums. This can allow the compiler to use faster dispatch, as the scope is limited.

class MyClass {
    private func privateMethod() {
        // ...
    }
}

Avoid frequent use of common protocols at runtime where specific types are unknown in advance, as calls through protocols use a virtual table. Prefer generics where possible at compile time.

Use the @inline(__always) attribute. This hint to the compiler attempts to inline the function body at the call site, avoiding the overhead of a function call. It does not always provide a benefit.

@inline(__always)
func myInlinedFunction() {
    // ...
}