sizeof

Sizeof是golang中获取指定类型占用字节的函数。比方slice构造占用的字节数为24(8+8+8)(以下均为64位cpu及64位操作系统下)

/**     type SliceHeader struct{      Data uintptr //8      Len  int //8      Cap  int //8    }

string为8+8

type StringHeader struct{         Data uintptr //8         Len int  //8     }

array为size(Type)*len,简略总结如下 。

type                      alignment guarantee------                    ------bool, uint8, int8         1uint16, int16             2uint32, int32             4float32, complex64        4arrays                    depend on element typesstructs                   depend on field typesother types               size of a native word

内存对齐及可视化工具

//main.gopackage maintype user struct {    name    string    age     int    gender  int    isBuy   bool    hobbies []string}type sliceCopy struct {    sInt    []int    sString []int}func main() {}

顺次执行

structlayout -json ./main.go sliceCopy  | structlayout-svg -t "sliceCopy" > sliceCopy.svg
structlayout -json ./main.go user | structlayout-svg -t "user" > user.svg

产出物为两个svg文件


如果不想看svg,还能够间接看ascii版本,须要以下命令

bogon:sizeOfCommonType w$ structlayout -json ./main.go user | structlayout-pretty

输入如下:

    +--------+  0 |        | <- user.name string (size 16, align 8)    +--------+    -........-    +--------+ 15 |        |    +--------+ 16 |        | <- user.age int (size 8, align 8)    +--------+    -........-    +--------+ 23 |        |    +--------+ 24 |        | <- user.gender int (size 8, align 8)    +--------+    -........-    +--------+ 31 |        |    +--------+ 32 |        | <- user.isBuy bool (size 1, align 1)    +--------+ 33 |        | <- padding (size 7, align 0)    +--------+    -........-    +--------+ 39 |        |    +--------+ 40 |        | <- user.hobbies []string (size 24, align 8)    +--------+    -........-    +--------+ 63 |        |    +--------+

所需包

go get -u honnef.co/go/tools//显示构造体布局go install honnef.co/go/tools/cmd/structlayout@latest//从新设计struct字段 缩小填充的数量go install honnef.co/go/tools/cmd/structlayout-optimize@latest// 用ASCII格局输入go install honnef.co/go/tools/cmd/structlayout-pretty@latest //第三方可视化go install github.com/ajstarks/svgo/structlayout-svg@latest

后续思考:

  1. 内存对齐的目标(使咱们能够开发出更高效的代码,使得cpu可高效拜访内存数据,)
  2. 构造体内存对齐的根本准则(小在前,大在后;空struct放在后面还是前面)
  3. 不同cpu硬件及不同os在32位和64位零碎如何兼容和实现原子指令的问题(aotmic包&?)