Constructors and initialization in C Sharp (C#) - Time & Space Complexity
When we create objects using constructors, some steps run to set up the object.
We want to see how the time needed changes as we create more objects or initialize more data.
Analyze the time complexity of the following code snippet.
public class Box
{
public int[] Items;
public Box(int size)
{
Items = new int[size];
for (int i = 0; i < size; i++)
{
Items[i] = i * 2;
}
}
}
// Creating a Box object
Box myBox = new Box(1000);
This code creates a Box object and fills an array with values during construction.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop inside the constructor that fills the array.
- How many times: It runs once for each element in the array, so size times.
As the size of the array grows, the number of steps to fill it grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps to fill the array |
| 100 | About 100 steps to fill the array |
| 1000 | About 1000 steps to fill the array |
Pattern observation: The work grows directly with the size of the array; doubling the size doubles the work.
Time Complexity: O(n)
This means the time to initialize grows in a straight line with the number of items we set up.
[X] Wrong: "Constructors always run in constant time no matter what."
[OK] Correct: If a constructor does work like filling an array, the time depends on how much data it handles, so it grows with input size.
Understanding how constructors scale helps you explain object setup costs clearly, a useful skill when discussing code efficiency.
"What if the constructor called another method that also loops over the array? How would the time complexity change?"