为什么要内存对齐
1.平台原因(移植原因):不是所有的硬件平台都能访问任意地址上的任意数据的;某些硬件平台只能
在某些地址处取某些特定类型的数据,否则抛出硬件异常。
2.性能原因:数据结构应该尽可能地在自然边界上对齐。原因在于,为了访问未对齐的内存,处理器需要作两次内存访问;而对齐的内存访问仅需要一次访问。(如果是对齐的,那么CPU不需要跨越两个操作字,不是对齐的则需要访问两个操作字才能拼接出需要的内存地址)
Go的数据结构对齐
大小保证
对齐保证
结构体对齐的一个例子
指针的大小一般是一个机器字的大小
type Ag struct { //64位系统
arr [2]int8 //2
bl bool //1 padding 5
sl []int16 //24 切片也是一个结构体由三个字段构成
ptr *int64 //8
st struct{ //16 string有两个字段
str string
}
m map[string]int16 //8
i interface{} //16 interface的iface或是eface都是两个指针
}
通过Go语言的structlayout工具,可以得出下图
type StringHeader struct {
Data uintptr
Len int
}
type SliceHeader struct {
Data uintptr
Len int
Cap int
}
// A header for a Go map.
type hmap struct {
// Note: the format of the hmap is also encoded in cmd/compile/internal/gc/reflect.go.
// Make sure this stays in sync with the compiler's definition.
count int // # live cells == size of map. Must be first (used by len() builtin)
flags uint8
B uint8 // log_2 of # of buckets (can hold up to loadFactor * 2^B items)
noverflow uint16 // approximate number of overflow buckets; see incrnoverflow for details
hash0 uint32 // hash seed
buckets unsafe.Pointer // array of 2^B Buckets. may be nil if count==0.
oldbuckets unsafe.Pointer // previous bucket array of half the size, non-nil only when growing
nevacuate uintptr // progress counter for evacuation (buckets less than this have been evacuated)
extra *mapextra // optional fields
}
//runtime/runtime2.go
type iface struct {
tab *itab //指向tab的指针
data unsafe.Pointer //指向数据的指针(unsave.Pointer可以储存任何变量地址)
}
type eface struct {
_type *_type
data unsafe.Pointer
}
这些类型在之前的slice、map、interface已经介绍过了,也特意强调过,makehmap函数返回的是一个指针,因此map的对齐为一个机器字.
Final zero
type T1 struct { //64位
a struct{}
x int64
}//8
type T2 struct { //final zero
x int64
a struct{}
} //16
//在go里会自动给a填充一个机器字,防止下一段内存数据对其产生影响
fmt.Println(unsafe.Sizeof(T1{}),unsafe.Sizeof(T2{}))
//8 16
回头看看 sync.pool的防止copy的空结构体字段,也是放在第一位,破案了。
type Pool struct {
noCopy noCopy
local unsafe.Pointer // local fixed-size per-P pool, actual type is [P]poolLocal
localSize uintptr // size of the local array
victim unsafe.Pointer // local from previous cycle
victimSize uintptr // size of victims array
// New optionally specifies a function to generate
// a value when Get would otherwise return nil.
// It may not be changed concurrently with calls to Get.
New func() interface{}
}
重排优化
(粗暴方式,按照对齐值得递减来重排成员)可以减少一些padding
内存地址对齐
计算机结构可能会要求内存地址 进行对齐;也就是说,一个变量的地址是一个因子的倍数,也就是该变量的类型是对齐值。
函数Alignof接受一个表示任何类型变量的表达式作为参数,并以字节为单位返回变量(类型)的对齐值。对于变量x:
内存对齐例子
type WaitGroup struct {
noCopy noCopy
// 64-bit value: high 32 bits are counter, low 32 bits are waiter count.
// 64-bit atomic operations require 64-bit alignment, but 32-bit
// compilers do not ensure it. So we allocate 12 bytes and then use
// the aligned 8 bytes in them as state, and the other 4 as storage
// for the sema.
state1 [3]uint32
//保证在32位系统上也是对齐的,保证原子操作
}
// state returns pointers to the state and sema fields stored within wg.state1.
func (wg *WaitGroup) state() (statep *uint64, semap *uint32) {
//判断地址是否8位对齐
if uintptr(unsafe.Pointer(&wg.state1))%8 == 0 {
//前8bytes做uint64指针statep,后4bytes做sema信号量
return (*uint64)(unsafe.Pointer(&wg.state1)), &wg.state1[2]
} else {//否则相反
return (*uint64)(unsafe.Pointer(&wg.state1[1])), &wg.state1[0]
}
}
64位字的安全访问保证
type willpanic struct {
init bool
uncounted int64
}
这是因为int64在bool之后未对齐。
它是32位对齐的,但不是64位对齐的,因为我们使用的是32位系统,因此实际上只是两个32位值并排在一起。
总结
● 内存对齐是为了cpu更高效访问内存中数据
● 结构体对齐依赖类型的大小保证和对齐保证
● 地址对齐保证是:如果类型 t 的对齐保证是 n,那么类型 t 的每个值的地址在运行时必须是 n 的倍数。
● struct内字段如果填充过多,可以尝试重排,使字段排列更紧密,减少内存浪费
● 零大小字段要避免作为struct最后一个字段,会有内存浪费
● 32位系统上对64位字的原子访问要保证其是8bytes对齐的;当然如果不必要的 话,还是用加锁(mutex)的方式更清晰简单