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

Why encapsulation matters in C Sharp (C#) - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why encapsulation matters
O(n)
Understanding Time Complexity

We want to see how using encapsulation affects the speed of a program.

Does hiding details inside a class change how long the program takes to run?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


public class Counter {
    private int count = 0;
    public void Increment() {
        count++;
    }
    public int GetCount() {
        return count;
    }
}

Counter c = new Counter();
for (int i = 0; i < n; i++) {
    c.Increment();
}
int total = c.GetCount();
    

This code uses a class to hide the count variable and updates it through methods.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop calling Increment() method.
  • How many times: Exactly n times, once per loop cycle.
How Execution Grows With Input

Each time n grows, the loop runs more times, increasing work linearly.

Input Size (n)Approx. Operations
1010 calls to Increment()
100100 calls to Increment()
10001000 calls to Increment()

Pattern observation: The work grows directly with n, doubling input doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the program takes longer in a straight line as the input size grows.

Common Mistake

[X] Wrong: "Encapsulation makes the program slower because method calls add extra steps."

[OK] Correct: The method calls add a tiny fixed cost, but the main work still depends on how many times the loop runs, not on hiding data.

Interview Connect

Understanding how encapsulation affects performance helps you write clean code without worrying about slowing things down.

Self-Check

"What if the Increment() method did more work inside, like logging each increment? How would the time complexity change?"