Why encapsulation is required in C++ - Performance Analysis
We want to understand how using encapsulation affects the time it takes for a program to run.
Specifically, does hiding data and controlling access change how fast our code works?
Analyze the time complexity of this simple class with encapsulation.
class Counter {
private:
int count;
public:
Counter() : count(0) {}
void increment() { count++; }
int getCount() { return count; }
};
void useCounter(int n) {
Counter c;
for (int i = 0; i < n; i++) {
c.increment();
}
int result = c.getCount();
}
This code defines a class that hides its data and provides methods to change and read it.
Look for loops or repeated actions that take time.
- Primary operation: The loop calling
increment()method. - How many times: Exactly
ntimes, wherenis input size.
Each time we increase n, the loop runs more times, doing one increment each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The work grows directly with n. Double n, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size.
[X] Wrong: "Encapsulation makes the program slower because of extra method calls."
[OK] Correct: The method calls are very fast and do not add extra loops or repeated work, so the overall time still grows linearly with input.
Understanding how encapsulation affects performance helps you write clean code without worrying about slowing things down.
What if the increment() method did more work inside, like searching a list? How would the time complexity change?