Dynamic dispatch vs Final

Dynamic dispatch vs Final

When working with classes in Swift, it gives you ability to override superclass methods and properties, which basically means that the compiler would have to infer for method/property implementation at runtime and perform direct call or indirect access, this technique is called Dynamic dispatch.

This technique increases performance overhead for a performance sensitive application.

We will see how we can reduce the dynamism by using final

Consider the following example:

class BankAccount {
    var balance: Double = 100000.0
    var interestRate: Double = 7.5
    
    func calculateInterest() {
        let interest = balance + (balance * interestRate/100)
        print(interest)
    }
    
    func performSecretOperation() {
        calculateInterest()
        print("this is secret implmention")
    }
}


let start = CFAbsoluteTimeGetCurrent()
var account = BankAccount()

for i in stride(from: 0.0, through: 3600000, by: 1.0) {
    account.performSecretOperation()
}
let diff = CFAbsoluteTimeGetCurrent() - start
print("Took \(diff) seconds")         

Before explaining how making the class final could impact, I would love to share how much

I ran the above code with different limits, 360, 3600, ... and following are the results

Article content

here is the graphical representation of the impact in seconds

Article content

Now let's talk about het how it just making the class final can reduce the execution time by ~47 sec in simple operations when done at larger count.

Making the class final, clears compiler head to look for any other implementation as now no other class could inherit and override any of the method, making is a static dispatch.

To view or add a comment, sign in

More articles by Deepak Singh

  • Mobile App Development Trends 2025: Building Smarter Apps with AI Automation

    Did you know that mobile app development trends are being dramatically reshaped by AI? According to the 2024…

  • Concurrency in Swift...

    If you haven't read the first piece in this series, please do. Since you've seen how to create any method async and…

  • Try and Fail in Swift

    Before you start searching for 'Fail' as a keyword in Swift, it's important to know that there isn't an actual 'Fail'…

  • Concurrency in Swift

    Swift has built-in support for writing asynchronous and parallel code in a structured way. Asynchronous code can be…

  • Dependency Injection: Basics

    What is It- Dependency Injection??? Literally: Ability to inject a dependency into an enclosed environment. This…

  • iOS meetup : Vadodara

    Hello iOS brain, I am an iOS developer. I am planning to organise a MEETUP for iOS developer.

    2 Comments

Explore content categories