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?"
Practice
go before a function call do in Go?Solution
Step 1: Understand the role of
Thegokeywordgokeyword in Go is used to start a new goroutine, which is a lightweight thread that runs concurrently with other goroutines.Step 2: Identify what happens when
Whengois used before a function callgois placed before a function call, that function runs asynchronously, allowing the program to continue without waiting for it to finish.Final Answer:
Starts the function as a new goroutine running concurrently -> Option AQuick Check:
gostarts concurrent execution [OK]
- Thinking 'go' delays function execution
- Confusing goroutine with method conversion
- Assuming 'go' runs function conditionally
doWork()?Solution
Step 1: Recall the syntax for starting a goroutine
In Go, to start a goroutine, you simply writegofollowed by the function call without parentheses or extra keywords.Step 2: Match the correct syntax
go doWork()usesgo doWork(), which is the exact syntax to start a goroutine. Other options use invalid keywords or extra words.Final Answer:
go doWork() -> Option BQuick Check:
Correct goroutine syntax = go function() [OK]
- Adding extra keywords like 'start' or 'run'
- Writing 'goroutine' instead of 'go'
- Missing parentheses after function name
package main
import (
"fmt"
"time"
)
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello()
fmt.Println("Hello from main")
time.Sleep(100 * time.Millisecond)
}Solution
Step 1: Understand goroutine and main execution order
ThesayHellofunction runs as a goroutine, so it runs concurrently with the main function. The main function prints first, then sleeps to allow the goroutine to run.Step 2: Analyze output order
Main prints "Hello from main" immediately. The goroutine prints "Hello from goroutine" during the sleep period, so both lines appear with main's message first.Final Answer:
Hello from main Hello from goroutine -> Option AQuick Check:
main prints first, goroutine runs during sleep [OK]
- Assuming goroutine always prints first
- Forgetting to add sleep to wait for goroutine
- Expecting no output because goroutine is async
func printNumber(n int) {
fmt.Println(n)
}
func main() {
go printNumber
}Solution
Step 1: Check goroutine syntax for function calls
When starting a goroutine, the function must be called with parentheses, even if it has parameters. Here,go printNumbermisses parentheses and argument.Step 2: Identify the specific syntax error
The code should bego printNumber(5)or some integer argument with parentheses to call the function properly as a goroutine.Final Answer:
Missing parentheses after function name in goroutine call -> Option CQuick Check:
Function call needs parentheses [OK]
- Omitting parentheses when calling function as goroutine
- Thinking goroutines can't have parameters
- Ignoring missing imports causing unrelated errors
for i := 1; i <= 3; i++ {
go func() {
fmt.Println(i)
}()
}Solution
Step 1: Understand closure capturing loop variable
The anonymous function captures the variableiby reference, so all goroutines print the final value (4) after the loop ends.Step 2: Fix by passing loop variable as parameter
Passingias a parameter to the anonymous function creates a new local copy for each goroutine, preserving the correct value.Final Answer:
Pass i as parameter to anonymous function: go func(n int) { fmt.Println(n) }(i) -> Option DQuick Check:
Pass loop variable as argument to fix closure [OK]
- Not passing loop variable, causing all goroutines to print same value
- Using global variables instead of parameters
- Relying on sleep to fix output order
Ready to prove it?
Pass the test and this pattern moves unknown
