GolangNote

Golang笔记

合理组织struct结构以节省内存占用

Permalink

struct 的排列不同,go 为其分配的内存空间也不同,下面的代码可以看到结果:

合理组织struct结构以节省内存占用

Go: struct 不同占用内存不同
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
	"fmt"
	"unsafe"
)

type myStruct struct {
	myInt   bool    // 1 byte
	myFloat float64 // 8 bytes
	myBool  int32   // 4 bytes
}

type myStructOptimized struct {
	myFloat float64 // 8 bytes
	myInt   int32   // 4 bytes
	myBool  bool    // 1 byte
}

func main() {
	a := myStruct{}
	b := myStructOptimized{}

	fmt.Println(unsafe.Sizeof(a)) // unordered 24 bytes
	fmt.Println(unsafe.Sizeof(b)) // ordered 16 bytes
}

下面的代码可以验证struct 的内存分配:

Go: 内存分配
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

import (
	"fmt"
	"unsafe"
)

type myStructOptimized struct {
	myFloat float64 // 8 bytes
	myBool  bool    // 1 byte
	myInt   int32   // 4 bytes

}

func main() {
	b := myStructOptimized{}
	
	fmt.Println(unsafe.Sizeof(b))
	fmt.Println(unsafe.Offsetof(b.myFloat))
	fmt.Println(unsafe.Offsetof(b.myBool))
	fmt.Println(unsafe.Offsetof(b.myInt))
}

resource How to organize the go struct, in order to save memory

Related articles

Write a Comment to "合理组织struct结构以节省内存占用"

Submit Comment Login
Based on Golang + fastHTTP + youdb | go1.16 Processed in 1ms