🚀 Why Does final Help Performance in Swift?
Swift uses two main types of method dispatch:
🖁 1. Dynamic Dispatch (via vtable)
• Used for regular (non-``) classes/methods
• Swift must look up the method implementation at runtime
• Slower, because methods can be overridden in subclasses
🚀 2. Static Dispatch (direct call)
• Used for `` classes/methods
• Compiler knows at compile time exactly what method to call
• Faster: no lookup needed, allows compiler optimizations like inlining
🧪 Example
class Parent {
func greet() {
print("Hello")
}
}
final class FinalWorker {
func work() {
print("Working fast!")
}
}
In the example above:
• [Link]() → Dynamic Dispatch
• [Link]() → Static Dispatch
⚡ Performance Benefit Summary
Feature Without final With final
Dispatch type Dynamic (vtable) Static (direct call)
Method override? Possible Not possible
1
Feature Without final With final
Optimization Limited Aggressive (inlining, etc.)
Execution speed Slower Faster
✅ When Should You Use final ?
Use final when:
• ✅ You don’t need inheritance
• ✅ You want better performance
• ✅ You want to lock down class behavior for safety
🚫 Avoid final If:
• 🔄 You need to allow subclassing and method overriding
🧠 Summary
• final eliminates dynamic dispatch
• Enables the compiler to optimize your code better
• Your code becomes both faster and safer from unintended overrides