Default case in select in Go - Time & Space Complexity
We want to understand how the time it takes to run a select statement with a default case changes as the program runs.
Specifically, how does adding a default case affect the waiting and checking in select?
Analyze the time complexity of the following code snippet.
select {
case msg := <-ch1:
fmt.Println(msg)
case ch2 <- 1:
fmt.Println("sent")
default:
fmt.Println("no communication")
}
This code tries to receive from ch1 or send to ch2, but if neither is ready, it runs the default case immediately.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The select statement checks channel readiness once per execution.
- How many times: Each select runs once per call, no waiting if default triggers.
Since select with default does not wait, the time per select is constant regardless of input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The time grows linearly with the number of select executions, but each select is a quick check.
Time Complexity: O(n)
This means the total time grows directly with how many times the select runs, but each run is fast because it never blocks.
[X] Wrong: "The default case makes select run instantly no matter what, so time is always constant."
[OK] Correct: While each select runs quickly, if you run select many times, total time still grows with the number of runs.
Understanding how select with default behaves helps you write responsive programs that don't block, a useful skill in concurrent programming.
What if we removed the default case? How would the time complexity change when channels are not ready?