ego008 avatar

优化struct 结构,减少内存分配

🕦 by ego008

代码

Go:
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
27
28
package main

import (
	"fmt"
	"unsafe"
)

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

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

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

	fmt.Println(unsafe.Sizeof(a)) // unordered 40 bytes
	fmt.Println(unsafe.Sizeof(b)) // ordered 32 bytes
}

原理:

来源 http://t.cn/RnQlAWM

💘 相关文章

写一条评论

Based on Golang + fastHTTP + sdb | go1.16.5 Processed in 0ms