Why understanding memory matters in C# - Performance Analysis
When we write C# programs, how fast they run often depends on how they use memory.
We want to know how memory use affects the speed of our code as it grows.
Analyze the time complexity of the following code snippet.
int[] numbers = new int[n];
for (int i = 0; i < n; i++)
{
numbers[i] = i * 2;
}
int sum = 0;
foreach (int num in numbers)
{
sum += num;
}
This code creates an array, fills it with values, then sums all values.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two loops over the array: one to fill, one to sum.
- How many times: Each loop runs exactly n times, where n is the array size.
As the array size grows, the number of steps grows in a simple way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 steps (10 to fill + 10 to sum) |
| 100 | About 200 steps |
| 1000 | About 2000 steps |
Pattern observation: The total steps grow roughly twice as fast as n, which means it grows in a straight line with n.
Time Complexity: O(n)
This means the time to run the code grows directly in proportion to the size of the input.
[X] Wrong: "Adding more memory (like bigger arrays) doesn't affect speed much."
[OK] Correct: More memory means more data to process, so loops take longer and the program runs slower as input grows.
Understanding how memory use affects speed helps you write better C# code and explain your thinking clearly in interviews.
"What if we replaced the array with a linked list? How would the time complexity change?"