1 回答

TA貢獻1871條經驗 獲得超13個贊
為什么創建成本是0?
Go 堆棧分配在堆上分配零字節。
mp := map[byte]byte{}
main map[byte]byte literal does not escape
package main
import (
? ? "fmt"
? ? "runtime"
)
func main() {
? ? var m1, m2 runtime.MemStats
? ? var i byte
? ? runtime.ReadMemStats(&m1)
? ? mp := map[byte]byte{}
? ? runtime.ReadMemStats(&m2)
? ? fmt.Println("Bytes allocated on creation:", m2.Alloc-m1.Alloc)
? ? for i = 0; i < 100; i++ {
? ? ? ? runtime.ReadMemStats(&m1)
? ? ? ? mp[i] = i
? ? ? ? runtime.ReadMemStats(&m2)
? ? ? ? fmt.Printf("Bytes allocated on assignment %d: %d\n", i, m2.Alloc-m1.Alloc)
? ? }
}
游樂場:https://play.golang.org/p/iyYshDzexQt
輸出:
Bytes allocated on creation: 0
- 1 回答
- 0 關注
- 167 瀏覽
添加回答
舉報