【问题标题】:Questions about goroutines performance关于 goroutines 性能的问题
【发布时间】:2022-09-24 20:28:05
【问题描述】:

我是 Golang 的新手,我想了解更多关于 goroutine 的知识。我将留下两个例子,我想知道这两个中哪一个更具表演性,为什么?

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
}

第一的:

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()
}

第二:

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()
}

有没有比这两个更好的方法?

如果不是,两者中哪一个性能更高?

  • 他们一开始就不是同一件事。 1 启动 5 个 goroutine 发出 5 个并行请求,另一个启动 1 个 goroutine 发出 5 个请求。第一个显然会更快,因为 5 个请求同时发生
  • ...除非服务器限制你,因为你在太短的时间内用太多的请求锤击它:)
  • 如果你想看看哪个性能更好,write a benchmark and test it
  • 在第二种情况下,您可以完全删除 go,因为没有任何优势:您调用一个 goroutine 并等待结束。它与test 函数中的循环基本相同。

标签: go goroutine


【解决方案1】:

go before function 是创建一个goroutine。

  1. 5 个 gouroutine,每个 goroutine 中有 1 个 doRequest()
  2. 1 个 gouroutine,5 个 doRequest() 在一个 goroutine

    在第一种情况下,5 个 goroutines 同时运行。

    我无法嵌入 img XD

【讨论】:

    猜你喜欢
    • 2011-05-28
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 2013-03-23
    • 1970-01-01
    • 2017-10-30
    相关资源
    最近更新 更多