go bytes.makeSlice 内存泄漏

新手上路,请多包涵

server:

package main

import (
    "bytes"

    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/pprof"
)

func main() {

    app := fiber.New()
    app.Use(pprof.New())
    app.Get("/test", func(c *fiber.Ctx) error {
        buffer := bytes.NewBufferString("")
        for i := 0; i < 1000000; i++ {
            buffer.WriteString("123")
        }
        return c.Send( buffer.Bytes())
    })

    if err := app.Listen(":9001"); err != nil {
        panic(err)
    }

}

client:

package main

import (
    "fmt"
    "net/http"
    "sync"
)

func main() {
    group := sync.WaitGroup{}
    for i := 0; i < 500; i++ {
        group.Add(1)
        go func(i interface{}) {
            client := http.Client{}
            response, err := client.Get("http://localhost:9001/test")
            if err != nil {
                return
            }

            b := make([]byte, 1)
            _, err = response.Body.Read(b)
            if err != nil {
                return
            }
            fmt.Print("run ", i)
            group.Done()
        }(i)
    }
    group.Wait()
}

内存占用:

λ go tool pprof http://127.0.0.1:9001/debug/pprof/heap?debug=1
Fetching profile over HTTP from http://127.0.0.1:9001/debug/pprof/heap?debug=1
Saved profile in 
Type: inuse_space
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top
Showing nodes accounting for 957.27MB, 98.64% of 970.49MB total
Dropped 42 nodes (cum <= 4.85MB)
Showing top 10 nodes out of 12
      flat  flat%   sum%        cum   cum%
  957.27MB 98.64% 98.64%   957.27MB 98.64%  bytes.makeSlice
         0     0% 98.64%   957.27MB 98.64%  bytes.(*Buffer).WriteString
         0     0% 98.64%   957.27MB 98.64%  bytes.(*Buffer).grow
         0     0% 98.64%   957.77MB 98.69%  github.com/gofiber/fiber/v2.(*App).handler
         0     0% 98.64%   957.27MB 98.64%  github.com/gofiber/fiber/v2.(*App).next
         0     0% 98.64%   957.27MB 98.64%  github.com/gofiber/fiber/v2.(*Ctx).Next
         0     0% 98.64%   957.27MB 98.64%  github.com/gofiber/fiber/v2/middleware/pprof.New.func1
         0     0% 98.64%   962.29MB 99.16%  github.com/valyala/fasthttp.(*Server).serveConn
         0     0% 98.64%   962.29MB 99.16%  github.com/valyala/fasthttp.(*workerPool).getCh.func1
         0     0% 98.64%   962.29MB 99.16%  github.com/valyala/fasthttp.(*workerPool).workerFunc

执行完成后,内存为什么一直不释放?

阅读 3.2k
1 个回答

漏了 response.Body.Close()

推荐问题