Home > Software engineering >  Questions about goroutines performance
Questions about goroutines performance

Time:09-27

I'm new to Golang, I would like to understand more about goroutine. I'll leave two examples and I wanted the opinion of which of the two is more performative and why?

func doRequest(method string, url string, body io.Reader) (*http.Response, error) {

    request, _ := http.NewRequest(method, url, body)
    
    response, err := c.httpClient.Do(request)
    request.Close = true
    c.httpClient.CloseIdleConnections()

    return response, err
}

first:

func test() {
    var wg *sync.WaitGroup = new(sync.WaitGroup)

    qtd := 5

    wg.Add(qtd)
    for i := 0; i < qtd; i   {
        go func(wg *sync.WaitGroup) {
            defer wg.Done()
            doRequest(http.MethodGet, "http://test.com", nil)

        }(wg)
    }
    wg.Wait()
}

Second:

func test() {
    var wg *sync.WaitGroup = new(sync.WaitGroup)

    wg.Add(1)
    go func(wg *sync.WaitGroup) {
        defer wg.Done()
        for i := 0; i < 5; i   {
            doRequest(http.MethodGet, "http://test.com", nil)
        }
    }(wg)

    wg.Wait()
}

Is there a better way than these two?

If not, which of the two is more performant?

CodePudding user response:

go before function is to create a goroutine.

  1. 5 gouroutines, 1 doRequest() in per goroutine
  2. 1 gouroutine, 5 doRequest() in a goroutine

In 1st case, 5 goroutines concurrently run.

I can't embed img XD

  • Related