Getter and setter methods in C++ - Time & Space Complexity
We want to see how the time it takes to run getter and setter methods changes as we use them more.
How does calling these methods affect the program's speed when the input size grows?
Analyze the time complexity of the following code snippet.
class Box {
private:
int value;
public:
int getValue() { return value; }
void setValue(int v) { value = v; }
};
void updateValues(Box boxes[], int n) {
for (int i = 0; i < n; i++) {
boxes[i].setValue(i);
}
}
This code defines simple getter and setter methods for a class and uses the setter in a loop to update many objects.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the setter method inside a loop.
- How many times: The setter is called once for each element in the array, so n times.
As the number of boxes (n) grows, the number of setter calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 setter calls |
| 100 | 100 setter calls |
| 1000 | 1000 setter calls |
Pattern observation: The work grows directly with the number of items; doubling n doubles the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of objects we update.
[X] Wrong: "Getter and setter methods always add extra hidden loops making the code slower."
[OK] Correct: These methods usually just read or write a value directly, so each call takes the same small time, no extra loops inside.
Understanding how simple methods like getters and setters affect performance helps you explain your code clearly and shows you know how to think about efficiency.
"What if the setter method included a loop inside it? How would the time complexity change?"