0
0
C Sharp (C#)programming~5 mins

Runtime polymorphism execution in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Runtime polymorphism execution
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run a program changes when using runtime polymorphism in C#.

Specifically, we ask: How does calling methods through polymorphism affect the number of steps the program takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


using System;

class Animal {
    public virtual void Speak() {
        Console.WriteLine("Animal speaks");
    }
}

class Dog : Animal {
    public override void Speak() {
        Console.WriteLine("Dog barks");
    }
}

void MakeAnimalsSpeak(Animal[] animals) {
    foreach (var animal in animals) {
        animal.Speak();
    }
}
    

This code calls the Speak method on each Animal object, using runtime polymorphism to decide which Speak version to run.

Identify Repeating Operations
  • Primary operation: The loop that calls Speak() on each animal in the array.
  • How many times: Once for each animal in the input array.
How Execution Grows With Input

Each animal in the array causes one method call. The program does a little extra work to find the right method at runtime.

Input Size (n)Approx. Operations
10About 10 method calls with runtime checks
100About 100 method calls with runtime checks
1000About 1000 method calls with runtime checks

Pattern observation: The number of operations grows directly with the number of animals. Each call has a small extra cost for deciding which method to run.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of animals, even with runtime polymorphism.

Common Mistake

[X] Wrong: "Runtime polymorphism makes the program run much slower, like quadratic time."

[OK] Correct: Each method call still happens once per item, with only a small extra step to find the right method. It does not multiply calls or loops.

Interview Connect

Understanding how runtime polymorphism affects performance shows you know how programs decide what to do while running. This skill helps you write clear and efficient code.

Self-Check

"What if we replaced the array with a nested loop calling Speak on each animal multiple times? How would the time complexity change?"