好好爱自己!

【转】GO 利用unsafe.Sizeof,Alignof,Offsetof理解内存对齐

 

原文: https://studygolang.com/articles/21827

-------------------------------------

 

以下讲解均在64位系统下进行

基础类型大小

typesize/bytes
bool 1
intN, uintN, floatN, complexN N/8
int, uint, uintptr 1
*T 1
string 2(data,len)
[]T 3(data,len,cap)
map 1
func 1
chan 1
interface 2

详解

先来看一段go代码

var x struct {
    a bool
    b int32
    c []int
}
  • 问: unsafe.sizeof(x)返回值是多少?

    第一次思考这个问题的时候,根据上面的基础类型大小我们可以知道,x的大小应该是sizeof(a) + sizeof(b) + sizeof(c) = 1 + 4 + 24 = 29

但是由于内存对齐的存在其实答案应该是32

如何理解内存对齐

先来都看一下每个成员的大小

var x struct {
    a bool
    b int32
    c []int
}
fmt.Println("SIZE")
fmt.Println(unsafe.Sizeof(x))
fmt.Println(unsafe.Sizeof(x.a))
fmt.Println(unsafe.Sizeof(x.b))
fmt.Println(unsafe.Sizeof(x.c))
fmt.Println("ALIGN")
fmt.Println(unsafe.Alignof(x))
fmt.Println(unsafe.Alignof(x.a))
fmt.Println(unsafe.Alignof(x.b))
fmt.Println(unsafe.Alignof(x.c))
fmt.Println("OFFSET")
fmt.Println(unsafe.Offsetof(x.a))
fmt.Println(unsafe.Offsetof(x.b))
fmt.Println(unsafe.Offsetof(x.c))
// Output:
// SIZE
// 32
// 1
// 4
// 24
// ALIGN
// 8
// 1
// 4
// 8
// OFFSET
// 0
// 4
// 8

https://play.golang.org/p/9wAjYyR04Rs

这里的关键点为理解Alignof的返回值:
// Alignof takes an expression x of any type and returns the required alignment
// of a hypothetical variable v as if v was declared via var v = x.
// It is the largest value m such that the address of v is always zero mod m.
我的理解是,以64位系统为例,m是使得v地址值始终是8(64/8)的倍数的最大值,也就是 8 mod n = 0,m = max(n)

64位地址的一个block是64 bit / 8 bit = 8bytes

从上面的输出来看x.a和x.b的m值相加都小于8所以他们俩可以分佩到一个block内,
所以a和b的sum of size = 8bytes,剩下的x.c大小为24bytes,
所以size of x = 8 + 24 = 32 bytes,num of block = 4

接下来我们看一下内存对齐的风险

var x struct {
    a int32
    b []int
    c bool //将类型前移,让c的类型为最小的bool
}
// Output:
// SIZE
// 40
// 4
// 24
// 1
// ALIGN
// 8
// 4
// 8
// 1
// OFFSET
// 0
// 8
// 32
可以注意到,x的大小变成了40,我们沿用前面的思想,
x.a的m为4但是其后的x.b的m为8,所以a和b的sum of size > 8bytes,
x.a就单独占用一个block,然后是x.b连续占用三个block,
最后x.c的m为1独占一个block,
所以size of x = 8 + 24 + 8 = 40 bytes,num of block = 5

为什么要内存对齐

CPU看待内存是以block为单位的,就像是linux下文件大小的单位IO block为4096一样,
是一种牺牲空间换取时间的做法.

总结

内存对齐是一种牺牲空间节约时间的做法,但是我们一定要注意不要浪费空间,
聚合类型定义的时候一定要将占用内从空间小的类型放在前面。

参考

go语言圣经

posted @ 2021-04-16 15:29  立志做一个好的程序员  阅读(268)  评论(0编辑  收藏  举报

不断学习创作,与自己快乐相处