Passing reference types to methods in C Sharp (C#) - Time & Space Complexity
When we pass reference types to methods, it's important to know how this affects the program's speed.
We want to see how the time to run changes as the input size grows.
Analyze the time complexity of the following code snippet.
void UpdateList(List<int> numbers) {
for (int i = 0; i < numbers.Count; i++) {
numbers[i] = numbers[i] * 2;
}
}
List<int> myNumbers = new List<int> {1, 2, 3, 4, 5};
UpdateList(myNumbers);
This code doubles each number in a list passed to a method.
- Primary operation: Looping through the list to update each element.
- How many times: Once for each item in the list (n times).
As the list gets bigger, the method takes longer because it updates every item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 updates |
| 100 | 100 updates |
| 1000 | 1000 updates |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line as the list gets bigger.
[X] Wrong: "Passing a reference type to a method makes the method run instantly regardless of list size."
[OK] Correct: Even though the method gets a reference, it still has to loop through all items, so time grows with list size.
Understanding how passing reference types affects time helps you explain code efficiency clearly and confidently.
"What if the method only updated the first 5 items regardless of list size? How would the time complexity change?"