Skip to content

Commit b852158

Browse files
committed
go: 性能优化建议
1 parent ed1976d commit b852158

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

go-note/optimize.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,13 @@ Go 性能优化
1010
- 优化反射。https://github.com/goccy/go-reflect
1111
- 减小锁消耗。减小锁粒度;使用原子操作(atomic)代替互斥锁
1212

13+
优化建议:
14+
15+
- 预分配内存。slice/map 如果预知容量信息,初始化应该提供,减少内存重分配和复制元素的消耗。 `make([]int, 0, cap); make(map[int]int, cap)`
16+
- 使用 strings.Builder 拼接大量字符串
17+
- 使用空的结构体作为占位符,空结构体 struct{} 不占内存。 比如实现 set 使用 map[string]struct{}{}
18+
- 使用 atomic 代替 sync 包
19+
1320
string 与 []byte 互转
1421
---------------------------------------------------------------
1522
利用了底层 string 和 byte slice 实现的技巧,如果需要大量互转可以使用这种方式。

0 commit comments

Comments
 (0)