为了账号安全,请及时绑定邮箱和手机立即绑定

在 golang 中声明一个空的 map[string]interface{} 的内存成本/开销是多

在 golang 中声明一个空的 map[string]interface{} 的内存成本/开销是多

Go
qq_花开花谢_0 2023-06-26 14:58:06
只是出于好奇,从源代码中询问type hmap struct {    count     int // 1 word    flags     uint8    B         uint8      noverflow uint16     hash0     uint32 // = 8 byte    buckets    unsafe.Pointer // 1 word    oldbuckets unsafe.Pointer // 1 word    nevacuate  uintptr        // 1 word    extra *mapextra // 1 word}所以它至少是:5个字+8个字节但为什么创建成本是0呢?-package mainimport (    "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 回答

?
慕桂英4014372

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


查看完整回答
反对 回复 2023-06-26
  • 1 回答
  • 0 关注
  • 85 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信