59

[译] Go语言结构体中属性的顺序将影响结构体的大小 | yoko blog

 5 years ago
source link: https://pengrl.com/p/16608/?
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

learn and live

[译] Go语言结构体中属性的顺序将影响结构体的大小

2019-09-01 | Go

在Go语言中,结构体的大小取决于内部属性的类型以及它们的排列顺序。

1
2
3
4
5
6
struct {
a bool
b int32
c string
d string
}

上面这个结构体的大小和下面这个结构体的大小是不同的,尽管它们只是属性的定义顺序不同。

1
2
3
4
5
6
struct {
b int32
c string
d string
a bool
}

为什么会这样?可以把内存想象成是由一个一个固定大小的小盒子组成的。如果结构体的某个属性的大小大于当前盒子剩余的大小,那个这个属性将填入下一个盒子中。这将造成上一个盒子的尾部空间没有被填入数据,但是却占用了内存。这种结构体初始化每个变量实例时都会有这种情况。

这里有一个非常棒的网站(http://golang-sizeof.tips/),你可以在这个网站上输入一个结构体的定义,然后查看内存布局。我们拿上面第一个结构体来看:

struct1

下面是第二个结构体的展示:

struct2

感谢这个网站。下次当你有一个非常大的结构体类型的数组时,就可以通过这个网站来估算数组的内存大小了。

英文链接: Preslav Rachev | Reduce Struct Size by Laying out Attributes Accordingly https://preslav.me/2019/08/27/reduce-struct-size-by-laying-out-attributes-accordingly/

本文完,作者yoko,尊重劳动人民成果,转载请注明原文出处: https://pengrl.com/p/16608/

推荐阅读:

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK