0
0
Goprogramming~5 mins

Goroutine creation - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Goroutine creation
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating a goroutine inside a loop.
  • How many times: Exactly n times, once per loop iteration.
How Execution Grows With Input

Each goroutine creation takes roughly the same time, so total time grows as we add more goroutines.

Input Size (n)Approx. Operations
1010 goroutine creations
100100 goroutine creations
10001000 goroutine creations

Pattern observation: The time to create goroutines grows directly with the number of goroutines.

Final Time Complexity

Time Complexity: O(n)

This means if you double the number of goroutines, the time to create them roughly doubles too.

Common Mistake

[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.

Interview Connect

Understanding how goroutine creation scales helps you write efficient concurrent programs and shows you grasp Go's concurrency model.

Self-Check

"What if we created goroutines inside nested loops? How would the time complexity change?"