what's the difference between static in dynamic dispatch?

Asked on 04/17/2025

1 search

Static dispatch and dynamic dispatch are two different methods of function call resolution in programming, particularly in Swift, as discussed in the Explore Swift performance session at WWDC 2024.

  • Static Dispatch: This occurs when the function to be called is determined at compile time. It is more efficient because it allows for optimizations like inlining and generic specialization. The compiler can see the function definition and optimize the call accordingly. Static dispatch is used when the function is declared in a protocol extension.

  • Dynamic Dispatch: This occurs when the function to be called is determined at runtime. It is less efficient than static dispatch because it doesn't allow for the same level of compile-time optimizations. However, dynamic dispatch enables polymorphism and other powerful tools for abstraction. In Swift, dynamic dispatch is used when a function is a protocol requirement, meaning it is declared in the main body of the protocol.

Understanding the difference between these two types of dispatch is crucial for optimizing performance and leveraging Swift's capabilities effectively.