0
0
Goprogramming~5 mins

Goroutine lifecycle - Time & Space Complexity

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

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Starting and running n goroutines.
  • How many times: Exactly n times, once per goroutine.
How Execution Grows With Input

As the number of goroutines n increases, the total work to start and complete them grows linearly.

Input Size (n)Approx. Operations
10About 10 goroutine starts and prints
100About 100 goroutine starts and prints
1000About 1000 goroutine starts and prints

Pattern observation: The total work grows directly with the number of goroutines.

Final Time Complexity

Time Complexity: O(n)

This means the time to start and complete all goroutines grows in a straight line as you add more goroutines.

Common Mistake

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

Interview Connect

Understanding how goroutine count affects execution time helps you write efficient concurrent programs and explain your reasoning clearly.

Self-Check

"What if each goroutine launched another goroutine inside it? How would the time complexity change?"