Goroutine creation - Time & Space Complexity
When we create many goroutines in Go, we want to know how the time to start them grows as we add more.
We ask: How does the cost of creating goroutines change when we increase their number?
Analyze the time complexity of the following code snippet.
for i := 0; i < n; i++ {
go func(id int) {
// some work here
}(i)
}
This code starts n goroutines, each doing some work concurrently.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a goroutine inside a loop.
- How many times: Exactly
ntimes, once per loop iteration.
Each goroutine creation takes roughly the same time, so total time grows as we add more goroutines.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 goroutine creations |
| 100 | 100 goroutine creations |
| 1000 | 1000 goroutine creations |
Pattern observation: The time to create goroutines grows directly with the number of goroutines.
Time Complexity: O(n)
This means if you double the number of goroutines, the time to create them roughly doubles too.
[X] Wrong: "Creating goroutines is instant and costs no time regardless of how many we start."
[OK] Correct: Each goroutine creation takes some time and resources, so more goroutines mean more total creation time.
Understanding how goroutine creation scales helps you write efficient concurrent programs and shows you grasp Go's concurrency model.
"What if we created goroutines inside nested loops? How would the time complexity change?"