Object creation and destruction flow in C++ - Time & Space Complexity
We want to understand how the time taken by a program changes when it creates and destroys objects.
How does the number of objects affect the total time spent on these actions?
Analyze the time complexity of the following code snippet.
class MyClass {
public:
MyClass() { /* constructor work */ }
~MyClass() { /* destructor work */ }
};
void createObjects(int n) {
for (int i = 0; i < n; ++i) {
MyClass obj;
}
}
This code creates and destroys n objects one after another inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating and destroying one object inside the loop.
- How many times: Exactly
ntimes, once per loop iteration.
Each object creation and destruction takes some fixed time. Doing this n times means the total time grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations + 10 destructions = 20 operations |
| 100 | 100 creations + 100 destructions = 200 operations |
| 1000 | 1000 creations + 1000 destructions = 2000 operations |
Pattern observation: When n doubles, total operations roughly double too.
Time Complexity: O(n)
This means the total time grows in a straight line as the number of objects increases.
[X] Wrong: "Creating and destroying objects inside a loop is constant time because each object is small."
[OK] Correct: Even if each object is small, doing it many times adds up. The total time depends on how many objects you create and destroy.
Understanding how object creation and destruction scale helps you reason about program speed and resource use in real projects.
What if we created objects dynamically with new inside the loop and deleted them after? How would the time complexity change?