gpt4 book ai didi

go - 内存使用情况: nil interface{} vs struct{}

转载 作者:行者123 更新时间:2023-12-02 16:31:00 25 4
gpt4 key购买 nike

我正在尝试了解有关内存使用情况的更多信息。

使用 interface{}struct{} slice 进行一些测试,我注意到 struct{} slice 未分配任何内存,而 interface{} slice 则可以。这对我来说没有多大意义,我实际上期望相同的行为(即两者都不分配任何内容)。无论如何,我找不到关于这个特殊案例的任何解释。

有人可以解释一下为什么会发生这种情况吗?

package main

import (
"runtime"
"fmt"
)

func main() {
// Below is an example of using our PrintMemUsage() function
// Print our starting memory usage (should be around 0mb)
fmt.Println("Start")
PrintMemUsage()
fmt.Println("")

structContainer := make([]struct{}, 1000000)
for i := 0; i<1000000; i++ {
structContainer[i] = struct{}{}
}

fmt.Println("With 1kk struct{}")
PrintMemUsage()
fmt.Println("")

nilContainer := make([]interface{}, 1000000)
for i := 0; i<1000000; i++ {
nilContainer[i] = nil
}

fmt.Println("With 1kk nil interface{}")
PrintMemUsage()
fmt.Println("")
}

// PrintMemUsage outputs the current, total and OS memory being used. As well as the number
// of garage collection cycles completed.
func PrintMemUsage() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
// For info on each, see: https://golang.org/pkg/runtime/#MemStats
fmt.Printf("Alloc = %v KiB", bToMb(m.Alloc))
fmt.Printf("\tTotalAlloc = %v KiB", bToMb(m.TotalAlloc))
fmt.Printf("\tSys = %v KiB", bToMb(m.Sys))
fmt.Printf("\tNumGC = %v\n", m.NumGC)
}

func bToMb(b uint64) uint64 {
return b / 1024
}

Playground link .

最佳答案

interface{} 类型的变量可以保存任何值。例如。它可以保存整数8,它可以保存字符串“hi”,它可以保存结构体值image.Point {X: 1, Y: 2} 以及几乎所有其他内容。

如果您分配一个以 interface{} 作为其元素类型的 slice ,则必须分配内存,以便您可以在其元素中存储任何值。当使用 make() 分配它时,它的所有元素都将获得该元素类型的零值(对于 interface{} 来说是 nil >),但仍然需要分配内存,否则以后无法设置元素。

另一方面,空结构体struct{}没有字段,它不能保存任何值(struct{}除外)。当您分配一个以 struct{} 作为其元素类型的 slice 时,不需要分配内存,因为您将无法在其中存储任何需要内存的内容。因此,不为这种类型分配内存是一个简单而聪明的优化。

关于go - 内存使用情况: nil interface{} vs struct{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59089869/

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