Blocking behavior in Go - Time & Space Complexity
When a program waits for something to finish before moving on, it is called blocking behavior.
We want to see how this waiting affects how long the program takes as the input grows.
Analyze the time complexity of the following code snippet.
package main
import (
"fmt"
"time"
)
func process(n int) {
for i := 0; i < n; i++ {
time.Sleep(10 * time.Millisecond) // simulate blocking
fmt.Println(i)
}
}
func main() {
process(5)
}
This code runs a loop that waits (blocks) for 10 milliseconds each time before printing a number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs and blocks (waits) inside each iteration.
- How many times: The loop runs exactly n times, each time waiting before continuing.
Each time the input n grows, the program waits longer because it blocks in every loop step.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 waits of 10ms each = about 100ms total wait |
| 100 | 100 waits of 10ms each = about 1 second total wait |
| 1000 | 1000 waits of 10ms each = about 10 seconds total wait |
Pattern observation: The total waiting time grows directly with the input size n.
Time Complexity: O(n)
This means the total time grows in a straight line as the input size increases because of the blocking waits.
[X] Wrong: "Blocking inside a loop doesn't affect overall time much because the program just waits quietly."
[OK] Correct: Waiting still takes real time, so if it happens many times, total time adds up and grows with input size.
Understanding blocking helps you explain how waiting steps affect program speed, a useful skill when discussing real-world code that handles files, networks, or user input.
"What if we replaced the blocking wait with a non-blocking operation? How would the time complexity change?"