When working with tasks that take time, using concurrency can help speed up your program. Go has a great way to run things at the same time using goroutines and channels. Here’s a simple example that compares how long a program takes to run with and without concurrency.
Sequential (Without Concurrency)
In this case, tasks like getting a user, product, and order are done one by one. This takes longer because each task waits for the previous one to finish:
user := getUser()
product := getProduct()
order := getOrder()
The total waiting time is the sum of all tasks in total 9 seconds.
With Concurrency
Using Go’s goroutines, we can run all the tasks at the same time. This makes the waiting time shorter:
go fetchUser(userChan)
go fetchProduct(productChan)
go fetchOrder(orderChan)
The tasks run in parallel, and the total waiting time is close to the longest task, not the sum of all tasks.
Results
Using concurrency, we can reduce waiting time from about 9 seconds to 3 seconds (if each task takes 3 seconds). This shows how concurrency can make Go programs much faster.