Why loops are needed in Go - Performance Analysis
Loops help us repeat actions many times without writing the same code again and again.
We want to see how the time to run code changes when we use loops with bigger inputs.
Analyze the time complexity of the following code snippet.
for i := 0; i < n; i++ {
println(i)
}
This code prints numbers from 0 up to n-1, repeating the print action n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The print statement inside the loop.
- How many times: Exactly n times, once for each loop cycle.
As n grows, the number of print actions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows directly with n, doubling n doubles the work.
Time Complexity: O(n)
This means the time to run the code grows in a straight line as the input size grows.
[X] Wrong: "The loop runs only once no matter how big n is."
[OK] Correct: The loop runs once for each number from 0 to n-1, so bigger n means more repeats.
Understanding how loops affect time helps you explain how your code handles bigger tasks clearly and confidently.
"What if we added a nested loop inside this loop? How would the time complexity change?"