golang内存对齐的重要性

 

结构体中字段类型的改变直接造成内存对齐结果的改变,是的占用内存空间也不一样

package main

import (
	"fmt"
	"unsafe"
)

func main() {

	var xx struct {
		a bool
		b int32
		c []int
	}

	var x struct {
		a int32
		b []int
		c bool
	}
	fmt.Println("SIZE")
	fmt.Println(unsafe.Sizeof(x))  //40
	fmt.Println(unsafe.Sizeof(xx)) //32
	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))
}

  

可以参考文章:https://juejin.cn/post/7077833959047954463

 

posted @ 2022-11-13 14:58  GPHPER  阅读(24)  评论(0编辑  收藏  举报
TOP