Array bounds checking behavior in C Sharp (C#) - Time & Space Complexity
When working with arrays, the program checks if each access is inside the allowed range.
We want to see how these checks affect the time it takes to run the code.
Analyze the time complexity of the following code snippet.
int[] numbers = new int[n];
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += numbers[i]; // Access with bounds check
}
return sum;
This code sums all elements in an array of size n, accessing each element once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing each array element inside a loop.
- How many times: Exactly n times, once per element.
- Additional operation: Each access includes a bounds check to ensure safety.
As the array size grows, the number of accesses and checks grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 accesses and 10 bounds checks |
| 100 | About 100 accesses and 100 bounds checks |
| 1000 | About 1000 accesses and 1000 bounds checks |
Pattern observation: The total work grows directly with n, doubling n doubles the work.
Time Complexity: O(n)
This means the time to complete the task grows in a straight line with the number of elements.
[X] Wrong: "Bounds checking adds extra loops or makes the code slower than linear."
[OK] Correct: Bounds checking happens during each access but does not add extra loops; it only adds a small constant check per element, so the overall time still grows linearly.
Understanding how array access and safety checks affect performance helps you explain code efficiency clearly and confidently.
What if we removed bounds checking by using unsafe code? How would the time complexity and safety change?