Why concurrency is needed in Go - Performance Analysis
Concurrency helps programs do many things at once, making them faster and more efficient.
We want to see how adding concurrency changes how long a program takes to run as it handles more work.
Analyze the time complexity of the following code snippet.
package main
import (
"fmt"
"time"
)
func work(id int) {
time.Sleep(1 * time.Second) // simulate work
fmt.Println("Work done", id)
}
func main() {
for i := 1; i <= 5; i++ {
work(i)
}
}
This code runs five tasks one after another, each taking about one second.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Running the
workfunction five times in a loop. - How many times: Exactly 5 times, one after another.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations (seconds) |
|---|---|
| 10 | 10 seconds |
| 100 | 100 seconds |
| 1000 | 1000 seconds |
Pattern observation: The total time grows directly with the number of tasks because they run one after another.
Time Complexity: O(n)
This means the total time increases in a straight line as you add more tasks, because each task waits for the previous one to finish.
[X] Wrong: "Running tasks one after another is just as fast as running them at the same time."
[OK] Correct: When tasks run one by one, total time adds up. Running tasks at the same time can save time by doing many things together.
Understanding how concurrency changes time helps you explain why programs can be faster and more efficient, a key skill in real-world coding.
"What if we changed the code to run all tasks concurrently using goroutines? How would the time complexity change?"