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

Why classes are needed in C Sharp (C#) - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why classes are needed
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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 Repeating Operations

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
How Execution Grows With Input

As the number of people (n) grows, the program does more work by creating and greeting each person.

Input Size (n)Approx. Operations
10About 10 greetings
100About 100 greetings
1000About 1000 greetings

Pattern observation: The work grows directly with the number of people.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as we add more people.

Common Mistake

[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.

Interview Connect

Understanding how classes affect program speed helps you explain your design choices clearly and shows you think about both structure and performance.

Self-Check

"What if we added a nested loop inside the SayHello method? How would the time complexity change?"