These days I wanted to speed up some data retrieval with Go. Its concurrency model is elegant and simple, it has everything you need built-in.
Let’s say there are some articles that need to be fetched from an API. I have the IDSs of all the articles, and I can fetch them one by one. One request can take even a second, so I added a 1 second sleep to simulate this.
type Article struct {
ID uint
Title string
}
func GetArticle(ID uint) Article {
time.Sleep(time.Second * 1)
return Article{ID, fmt.Sprintf("Title %d", ID)}
}
The classic way of doing this is making a request for each article, wait for it to finish, store the data.
var articles []Article
var id uint
for id = 1; id <= 10; id++ {
log.Println(fmt.Sprintf("Fetching article %d...", id))
article := GetArticle(id)
articles = append(articles, article)
}
log.Println(articles)
With a 1 second response time it takes 10 seconds. Now imagine 100 articles or more. Continue reading Go concurrency is elegant and simple