Why classes are needed in C Sharp (C#) - Performance Analysis
We want to understand how using classes affects the time it takes for a program to run.
Specifically, we ask: does organizing code with classes change how fast it runs as the program grows?
Analyze the time complexity of the following code snippet.
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public void SayHello()
{
Console.WriteLine($"Hello, my name is {Name}.");
}
}
var people = new List();
for (int i = 0; i < n; i++)
{
people.Add(new Person { Name = $"Person{i}", Age = 20 + i });
}
foreach (var person in people)
{
person.SayHello();
}
This code creates a list of people using a class, then each person says hello.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of people to call SayHello()
- How many times: Once for each person, so n times
As the number of people (n) grows, the program does more work by creating and greeting each person.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 greetings |
| 100 | About 100 greetings |
| 1000 | About 1000 greetings |
Pattern observation: The work grows directly with the number of people.
Time Complexity: O(n)
This means the time to run grows in a straight line as we add more people.
[X] Wrong: "Using classes makes the program slower because of extra steps."
[OK] Correct: Classes organize code but do not add hidden loops; the main time depends on how many times you run actions, not on using classes.
Understanding how classes affect program speed helps you explain your design choices clearly and shows you think about both structure and performance.
"What if we added a nested loop inside the SayHello method? How would the time complexity change?"