Runtime polymorphism execution in C Sharp (C#) - Time & Space 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?
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.
- Primary operation: The loop that calls
Speak()on each animal in the array. - How many times: Once for each animal in the input array.
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 |
|---|---|
| 10 | About 10 method calls with runtime checks |
| 100 | About 100 method calls with runtime checks |
| 1000 | About 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.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of animals, even with runtime polymorphism.
[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.
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.
"What if we replaced the array with a nested loop calling Speak on each animal multiple times? How would the time complexity change?"