Why methods are needed in C Sharp (C#) - Performance Analysis
We want to see how using methods affects how long a program takes to run.
Does breaking code into methods change how the program grows with bigger inputs?
Analyze the time complexity of the following code snippet.
class Program
{
static void PrintNumbers(int n)
{
for (int i = 0; i < n; i++)
{
Console.WriteLine(i);
}
}
static void Main()
{
PrintNumbers(1000);
}
}
This code prints numbers from 0 up to n-1 using a method called PrintNumbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop inside the PrintNumbers method.
- How many times: It runs n times, once for each number to print.
As n grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times printing |
| 100 | 100 times printing |
| 1000 | 1000 times printing |
Pattern observation: The work grows directly with n. If n doubles, work doubles.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size.
[X] Wrong: "Using methods makes the program slower or more complex."
[OK] Correct: Methods just organize code; they don't add extra loops or slow down the main work.
Understanding how methods affect time helps you write clear code without worrying about hidden slowdowns.
"What if the method called itself recursively instead of using a loop? How would the time complexity change?"