2 回答

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊
是的。內(nèi)存將被保留,直到不再有任何對(duì)分配的任何部分的引用。
通常的例子在切片技巧中給出
切片技巧
刪除而不保留順序
a[i]?=?a[len(a)-1]? a?=?a[:len(a)-1]NOTE 如果元素的類型是指針或帶指針字段的結(jié)構(gòu)體,需要進(jìn)行垃圾回收,上述Cut和Delete的實(shí)現(xiàn)存在潛在的內(nèi)存泄漏問(wèn)題:一些有值的元素仍然被切片a引用,從而無(wú)法收集。

TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
看profiler,好像確實(shí)是內(nèi)存泄露(go1.11.5 darwin/amd64)
讓我們看看探查器。
我在網(wǎng)上找到了調(diào)試內(nèi)存的例子。通過(guò)適應(yīng)我的示例,我這樣做了:
package main
import (
? ? "fmt"
? ? "os"
? ? "runtime"
? ? "runtime/debug"
? ? "runtime/pprof"
)
const aLot = 5000000
func getInteriorPointer() *int {
? ? type bigStruct struct {
? ? ? ? someBigThing [aLot]int
? ? ? ? smallThing? ?int
? ? }
? ? b := bigStruct{smallThing: 3}
? ? return &b.smallThing
}
func main() {
? ? p := getInteriorPointer()
? ? runtime.GC()
? ? debug.FreeOSMemory()
? ? fmem, _ := os.Create("prof.prof")
? ? pprof.WriteHeapProfile(fmem)
? ? // keep using p in the rest of the app,
? ? // never using someBigThing from the struct
? ? fmt.Println(*p)
}
現(xiàn)在我go tool pprof prof.prof跑list main
ROUTINE ======================== main.getInteriorPointer in /Users/karel/exp/exp.go
? ?38.15MB? ? 38.15MB (flat, cum)? ?100% of Total
? ? ? ? ?.? ? ? ? ? .? ? ?13:func getInteriorPointer() *int {
? ? ? ? ?.? ? ? ? ? .? ? ?14:? ?type bigStruct struct {
? ? ? ? ?.? ? ? ? ? .? ? ?15:? ? ? ? ? ?someBigThing [aLot]int
? ? ? ? ?.? ? ? ? ? .? ? ?16:? ? ? ? ? ?smallThing? ?int
? ? ? ? ?.? ? ? ? ? .? ? ?17:? ?}
? ?38.15MB? ? 38.15MB? ? ?18:? ?b := bigStruct{smallThing: 3}
? ? ? ? ?.? ? ? ? ? .? ? ?19:? ?return &b.smallThing
? ? ? ? ?.? ? ? ? ? .? ? ?20:}
? ? ? ? ?.? ? ? ? ? .? ? ?21:
? ? ? ? ?.? ? ? ? ? .? ? ?22:func main() {
? ? ? ? ?.? ? ? ? ? .? ? ?23:? ?p := getInteriorPointer()
ROUTINE ======================== main.main in /Users/karel/exp/exp.go
? ? ? ? ?0? ? 38.15MB (flat, cum)? ?100% of Total
? ? ? ? ?.? ? ? ? ? .? ? ?18:? ?b := bigStruct{smallThing: 3}
? ? ? ? ?.? ? ? ? ? .? ? ?19:? ?return &b.smallThing
? ? ? ? ?.? ? ? ? ? .? ? ?20:}
? ? ? ? ?.? ? ? ? ? .? ? ?21:
? ? ? ? ?.? ? ? ? ? .? ? ?22:func main() {
? ? ? ? ?.? ? 38.15MB? ? ?23:? ?p := getInteriorPointer()
? ? ? ? ?.? ? ? ? ? .? ? ?24:? ?runtime.GC()
? ? ? ? ?.? ? ? ? ? .? ? ?25:? ?debug.FreeOSMemory()
? ? ? ? ?.? ? ? ? ? .? ? ?26:? ?fmem, _ := os.Create("prof.prof")
? ? ? ? ?.? ? ? ? ? .? ? ?27:? ?pprof.WriteHeapProfile(fmem)
? ? ? ? ?.? ? ? ? ? .? ? ?28:
垃圾收集器似乎確實(shí)沒(méi)有從內(nèi)存中刪除不需要的對(duì)象。如果我正確理解格式。(我可能不會(huì),因?yàn)閹缀鯖](méi)有文檔。)
- 2 回答
- 0 關(guān)注
- 161 瀏覽
添加回答
舉報(bào)