gpt4 book ai didi

go - golang中byte[]转string奇怪占用堆

转载 作者:IT王子 更新时间:2023-10-29 01:35:03 24 4
gpt4 key购买 nike

我发现用下面的代码将 byte[] 转换为字符串时奇怪的占用堆

package main

import (
"bytes"
"fmt"
"net/http"
_ "net/http/pprof"
"strings"
"time"
)

var (
c = make(chan int, 500000)
)

func main() {
go func() {
http.ListenAndServe(":8080", nil)
}()
f := func(ss []string) {
fmt.Println(ss)
time.Sleep(time.Millisecond)
<-c
}
for {
c <- 1
bs := bytes.NewBufferString("A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z").Bytes()
fmt.Println(bs) // will raise memory leak after marked as comment???
s := string(bs)
ss := strings.Split(s, ",")
go f(ss)
}
}
  1. 没有fmt.Println(bs)会逐渐耗尽内存。

  2. fmt.Println(bs) 工作正常。我不明白发生了什么事?我正在使用 version go1.9.2 darwin/amd64

最佳答案

没有,没有没有内存泄漏:
您正在使用 500000 个并发 goroutine,您只需要限制(减少)并发 goroutine 的数量,例如:

c := make(chan int, runtime.NumCPU())

试试这个(并查看此编辑的结尾):

package main

import (
"bytes"
"fmt"
"runtime"
"strings"
"time"
)

func main() {
c := make(chan int, runtime.NumCPU())
for {
c <- 1
bs := bytes.NewBufferString("A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z").Bytes()
s := string(bs)
ss := strings.Split(s, ",")
go func(ss []string) {
fmt.Println(ss)
time.Sleep(time.Millisecond)
<-c
}(ss)
}
}

您的代码:

package main

import (
"bytes"
"fmt"
"net/http"
_ "net/http/pprof"
"strings"
"time"
)

var (
c = make(chan int, 500000)
)

func main() {
go func() {
http.ListenAndServe(":8080", nil)
}()
f := func(ss []string) {
fmt.Println(ss)
time.Sleep(time.Millisecond)
<-c
}
for {
c <- 1
bs := bytes.NewBufferString("A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z").Bytes()
// fmt.Println(bs) // will raise memory leak after marked as comment???
s := string(bs)
ss := strings.Split(s, ",")
go f(ss)
}
}

它在一段时间后达到稳定状态,甚至减少内存使用:

// Mem          CPU time:
// 5,464,208K 0:1:20
// 5,468,208K 0:2:20
// 5,469,608K 0:3:20
// 5,469,844K 0:4:20
// 5,469,844K 0:5:20
// 5,469,848K 0:6:20
// 5,469,848K 0:7:20 fixed
// 5,469,848K 0:8:20 fixed
// 5,469,616K 0:9:20 reduced

关于go - golang中byte[]转string奇怪占用堆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47615543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com