2 回答

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

TA貢獻1936條經驗 獲得超7個贊
看profiler,好像確實是內存泄露(go1.11.5 darwin/amd64)
讓我們看看探查器。
我在網上找到了調試內存的例子。通過適應我的示例,我這樣做了:
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)
}
現在我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:
垃圾收集器似乎確實沒有從內存中刪除不需要的對象。如果我正確理解格式。(我可能不會,因為幾乎沒有文檔。)
- 2 回答
- 0 關注
- 175 瀏覽
添加回答
舉報