When to use abstract vs concrete in C Sharp (C#) - Performance Comparison
We want to understand how choosing abstract or concrete classes affects the time your program takes to run.
Specifically, how does this choice impact the number of steps your program performs as it grows?
Analyze the time complexity of this example using abstract and concrete classes.
abstract class Animal
{
public abstract void Speak();
}
class Dog : Animal
{
public override void Speak() => Console.WriteLine("Woof");
}
class Program
{
static void MakeAnimalsSpeak(List animals)
{
foreach (var animal in animals)
animal.Speak();
}
}
This code uses an abstract class Animal with a Speak method, and a concrete class Dog that implements it. The program calls Speak on a list of animals.
Look at what repeats when the program runs.
- Primary operation: Calling the Speak method on each animal in the list.
- How many times: Once for each animal in the list (loop runs n times).
As the number of animals grows, the program calls Speak more times.
| 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 with the number of animals.
[X] Wrong: "Using abstract classes makes the program slower because of extra method calls."
[OK] Correct: The extra method call cost is very small and does not change how the total time grows with input size.
Understanding when to use abstract versus concrete classes shows you can design clear, flexible code without hurting performance as your program grows.
What if we replaced the abstract class with interfaces? How would the time complexity change?