0% found this document useful (0 votes)
5 views2 pages

Swift Performance: Benefits of Final Classes

Using 'final' in Swift classes improves performance by eliminating dynamic dispatch and allowing static dispatch, which enables compiler optimizations like inlining. It is recommended when inheritance is not needed, and better performance and safety are desired. However, 'final' should be avoided if subclassing and method overriding are required.

Uploaded by

jetaci2639
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Swift Performance: Benefits of Final Classes

Using 'final' in Swift classes improves performance by eliminating dynamic dispatch and allowing static dispatch, which enables compiler optimizations like inlining. It is recommended when inheritance is not needed, and better performance and safety are desired. However, 'final' should be avoided if subclassing and method overriding are required.

Uploaded by

jetaci2639
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

🚀 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

You might also like