转投go系列-go语言需要注意的地方-结构体字段顺序对其

最近发现公司代码很多人定义结构体的时候不注意字段对其
如下:

type AuditTaskTemplateDetail struct {
    
    
	IsTemplate   bool          `json:"isTemplate"` //1 byte
	TemplateName string        `json:"templateName"` //16 byte
	BatchCount   int32           `json:"batchCount"` //4 byte
}


看起来上面好像占用的空间都是 21字节,但是结果却不是这样。如果使用 GOARCH=amd64 编译代码,发现 AuditTaskTemplateDetail 类型占用 32 个字节,因为数据结构对齐,感兴趣的可以搜搜。在 64 位体系结构中,内存分配连续的 8 字节数据,所以不对齐的会被自动填充。
那么如何定义才是最好的,下面就是答案:

type AuditTaskTemplateDetail struct {
    
    
	TemplateName string        `json:"templateName"` //16 byte
	BatchCount   int32           `json:"batchCount"` //4 byte
	IsTemplate   bool          `json:"isTemplate"` //1 byte
}

当然,调整struct有工具叫fieldalignment,具体使用方法可以看看这篇文章。

手摸手Go 你的内存对齐了吗?

猜你喜欢

转载自blog.csdn.net/lwcbest/article/details/121350442