Goroutine lifecycle - Time & Space Complexity
When working with goroutines, it is important to understand how their execution time grows as we create more of them.
We want to know how the time cost changes when the number of goroutines increases.
Analyze the time complexity of the following code snippet.
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
n := 5
wg.Add(n)
for i := 0; i < n; i++ {
go func(i int) {
defer wg.Done()
fmt.Println(i)
}(i)
}
wg.Wait()
}
This code launches n goroutines, each printing a number, and waits for all to finish.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Starting and running
ngoroutines. - How many times: Exactly
ntimes, once per goroutine.
As the number of goroutines n increases, the total work to start and complete them grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 goroutine starts and prints |
| 100 | About 100 goroutine starts and prints |
| 1000 | About 1000 goroutine starts and prints |
Pattern observation: The total work grows directly with the number of goroutines.
Time Complexity: O(n)
This means the time to start and complete all goroutines grows in a straight line as you add more goroutines.
[X] Wrong: "Starting many goroutines happens instantly and does not add time."
[OK] Correct: Each goroutine takes some time to start and run, so more goroutines mean more total work and time.
Understanding how goroutine count affects execution time helps you write efficient concurrent programs and explain your reasoning clearly.
"What if each goroutine launched another goroutine inside it? How would the time complexity change?"