关于golang:golang-中Sizeof函数-与内存对齐查看的方式

8次阅读

共计 1684 个字符,预计需要花费 5 分钟才能阅读完成。

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         1
uint16, int16             2
uint32, int32             4
float32, complex64        4
arrays                    depend on element types
structs                   depend on field types
other types               size of a native word

内存对齐及可视化工具

//main.go
package main

type 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 包 &?)
正文完
 0