0
0
Swiftprogramming~5 mins

Base class and subclass in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Base class and subclass
O(n)
Understanding Time Complexity

When using base classes and subclasses, it's important to see how the program's work grows as input changes.

We want to know how the time to run the code changes when we create or use many objects.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Animal {
    func speak() {
        print("Animal sound")
    }
}

class Dog: Animal {
    override func speak() {
        print("Bark")
    }
}

let dogs = (1...n).map { _ in Dog() }
dogs.forEach { $0.speak() }
    

This code creates n Dog objects and calls their speak method one by one.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating n Dog objects and calling speak on each.
  • How many times: The speak method is called once for each Dog, so n times.
How Execution Grows With Input

As the number of Dog objects increases, the total work grows in a straight line.

Input Size (n)Approx. Operations
10About 10 speak calls
100About 100 speak calls
1000About 1000 speak calls

Pattern observation: Doubling n doubles the work because each object is handled once.

Final Time Complexity

Time Complexity: O(n)

This means the time grows directly with the number of objects created and used.

Common Mistake

[X] Wrong: "Because of inheritance, the code runs slower exponentially as n grows."

[OK] Correct: Inheritance itself does not add extra loops or repeated work; each object is still handled once.

Interview Connect

Understanding how subclassing affects time helps you explain object-oriented code performance clearly and confidently.

Self-Check

"What if the speak method called another method that loops over all dogs? How would the time complexity change?"