Collection initialization syntax in C Sharp (C#) - Time & Space Complexity
When we create collections using initialization syntax, it's helpful to know how the time to build them grows as we add more items.
We want to understand how the number of items affects the work done during collection setup.
Analyze the time complexity of the following code snippet.
var numbers = new List<int> { 1, 2, 3, 4, 5 };
// This creates a list and adds 5 numbers to it using collection initialization syntax.
This code creates a list and adds each number one by one during initialization.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each item to the list one at a time.
- How many times: Once for each item in the collection (5 times here).
Each new item means one more add operation. So if you double the items, you double the work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 adds |
| 100 | 100 adds |
| 1000 | 1000 adds |
Pattern observation: The work grows directly with the number of items added.
Time Complexity: O(n)
This means the time to create the collection grows in a straight line with the number of items you add.
[X] Wrong: "Collection initialization adds all items instantly, so time doesn't grow with more items."
[OK] Correct: Each item is added one by one, so more items mean more work and more time.
Understanding how collection initialization scales helps you explain performance when building lists or arrays in real projects.
What if we changed from a List to a LinkedList? How would the time complexity change when initializing with many items?