Object instantiation with new in C Sharp (C#) - Time & Space Complexity
When we create new objects in C#, it's helpful to know how this affects the time our program takes to run.
We want to see how the time changes as we make more objects using new.
Analyze the time complexity of the following code snippet.
class Item {}
void CreateItems(int n) {
for (int i = 0; i < n; i++) {
Item item = new Item();
}
}
This code creates n new Item objects one after another in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a new
Itemobject inside the loop. - How many times: Exactly
ntimes, once per loop iteration.
Each time we increase n, we create more objects, so the work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations |
| 100 | 100 object creations |
| 1000 | 1000 object creations |
Pattern observation: The number of operations grows in a straight line as n grows.
Time Complexity: O(n)
This means the time to create objects grows directly in proportion to how many objects we make.
[X] Wrong: "Creating objects with new is instant and does not affect time as n grows."
[OK] Correct: Each object creation takes some time, so more objects mean more total time.
Understanding how object creation scales helps you reason about program speed and resource use in real projects.
"What if we created objects inside a nested loop instead of a single loop? How would the time complexity change?"