Sometimes, small code changes can bring considerable benefits.
By using specific keywords, we can improve the performance of our code.
Before I reveal that little optimization trick, you need to understand why it actually works.
So, let’s talk first about method calls.
Swift supports different techniques to invoke a method at runtime.
Static dispatch is when the compiler can infer at build time which method to call.
Static dispatch won’t work if subclasses can override the methods or the properties of the superclass. The compiler can’t figure out at compile time whether we’re referring to the superclass’s implementation or the implementation of one of its subclasses.
The runtime needs to inspect the class hierarchy while the program is executing to find out which method to invoke. This is the dynamic dispatch mechanism.
Dynamic dispatch introduces some overhead, which makes it slower compared to the static dispatch. Besides, static dispatch allows for compiler optimizations which are not possible with dynamic dispatch.
We’re talking about tiny differences per method call, but these times may add up in complex apps or frameworks.
However, here’s the good news: we can use the final keyword to prevent a method or property from being overridden. That reduces the dynamic behavior.
We can even mark the entire class as final, which enables static dispatch for that class.
Only mark a class as final if you don’t intend to subclass it!
We can reduce dynamic dispatch also by marking the methods and the properties we do not want to expose as private. The private keyword hides the declaration, and as such, it cannot be overridden.
Consider the effects of these changes before actually performing them. Do not ruin your design to gain a couple of milliseconds here and there.
While reducing dynamic dispatch speeds up your programs, the real bottleneck is usually the code itself. Optimizing your algorithms and data structures can bring huge performance improvements. If you want to find out more about this topic, check out my course ‘Introduction to Algorithms and Data Structures in Swift 4’.
I’m offering a personal coupon to get the course for only $9.99. This is the lowest price I’ll ever offer it for.
Get the course at this link https://www.udemy.com/introduction-to-algorithms-in-swift/?couponCode=LEAKKA2018 or use the coupon code LEAKKA2018