Why polymorphism matters in C Sharp (C#) - Performance Analysis
We want to see how using polymorphism affects the time it takes for a program to run.
Does choosing polymorphism change how fast the program works as it handles more data?
Analyze the time complexity of the following code snippet.
public abstract class Animal {
public abstract void Speak();
}
public class Dog : Animal {
public override void Speak() { Console.WriteLine("Woof"); }
}
public class Cat : Animal {
public override void Speak() { Console.WriteLine("Meow"); }
}
public void MakeAnimalsSpeak(List animals) {
foreach (var animal in animals) {
animal.Speak();
}
}
This code calls the Speak method on a list of animals using polymorphism.
- Primary operation: Looping through each animal and calling Speak()
- How many times: Once for each animal in the list (n times)
As the number of animals grows, the program calls Speak() more times, once per animal.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to Speak() |
| 100 | 100 calls to Speak() |
| 1000 | 1000 calls to Speak() |
Pattern observation: The number of operations grows directly with the number of animals.
Time Complexity: O(n)
This means the time to run grows in a straight line as you add more animals.
[X] Wrong: "Polymorphism makes the program slower because it adds extra steps."
[OK] Correct: The extra step is just one method call per item, so it grows linearly and does not slow down the program in a big way.
Understanding how polymorphism affects time helps you explain your design choices clearly and confidently in real projects.
"What if we added nested loops inside each Speak method? How would the time complexity change?"