Go GC 优化

Go 1.19之前

https://www.cnblogs.com/luozhiyun/p/16685039.html

https://blog.twitch.tv/en/2019/04/10/go-memory-ballast-how-i-learnt-to-stop-worrying-and-love-the-heap/

Go GC优化之路(毛老师)

https://xargin.com/the-new-api-for-heap-limit/

Ballast

压舱石

现在应该清楚的是,任何涉及分配的 goroutine 都会在 GC 循环期间招致 GCAssist 惩罚。 由于工作必须在分配之前完成,这将表现为 goroutine 打算做的实际有用工作的延迟或缓慢。

在我们的 API 前端,这意味着 API 响应在 GC 周期中会增加延迟。 如前所述,随着每个服务器的负载增加,内存分配率会增加,这反过来会增加 GC 周期率(通常为 10 秒或 20 秒周期/秒)。 我们现在知道,更多的 GC 周期意味着服务于 API 的 goroutine 需要更多的 GC 辅助工作,因此也就意味着更多的 API 延迟。

你可能想知道为什么 Go 会为它的 GC 选择这样一个奇怪的设计(使用辅助),但它实际上很有意义。 GC 的主要功能是确保我们将堆保持在合理的大小,并且不会让它不受垃圾约束地增长。这在 stop-the-world (STW) GC 中很容易,但在并发 GC 中,我们需要一种机制来确保在 GC 周期中发生的分配不会无限制地增长。在我看来,让每个 goroutine 支付与其想要在 GC 周期中分配的内容成比例的分配税是一个非常优雅的设计。

https://stackoverflow.com/questions/24863164/how-to-analyze-golang-memory

https://www.reddit.com/r/golang/comments/junupo/if_go_could_turn_off_its_gc_optionally_like/

https://golang-nuts.narkive.com/IwLJ8o3x/reverseproxy-performance-and-gc

几行代码为老板省百万-某高并发服务GOGC及UDP Pool优化

Go的gc分几个阶段?每个阶段工作是什么,大致用时是什么数量级?哪些需要stw,哪些可以和用户程序并行执行?怎样解决回收的内存跟不上新申请的速度?…混合写屏障满足强三色标记还是弱三色标记?

一般都卷不到这程度

https://golang.design/under-the-hood/zh-cn/part2runtime/ch08gc/history/

https://draveness.me/golang/docs/part3-runtime/ch07-memory/golang-garbage-collector/

threadCreates := 0
if tcProf := pprof.Lookup("threadcreate"); tcProf != nil {
	threadCreates = tcProf.Count()
}

numMutex := 0
if mutexProf := pprof.Lookup("mutex"); mutexProf != nil {
	numMutex = mutexProf.Count()
}

numBlock := 0

if blockProf := pprof.Lookup("block"); blockProf != nil {
	numBlock = blockProf.Count()
}

return collector.NewRow(
	collector.NewColumn("numCPU", runtime.NumCPU()),
	collector.NewColumn("numCgo", runtime.NumCgoCall()), //调用c代码的次数
	collector.NewColumn("numGoroutine", runtime.NumGoroutine()),
	collector.NewColumn("numThreadCreate", threadCreates), //创建的线程数
	collector.NewColumn("numMutex", numMutex),
	collector.NewColumn("numBlock", numBlock),
)

GOGC Tuner

https://eng.uber.com/how-we-saved-70k-cores-across-30-mission-critical-services/

https://github.com/cch123/gogctuner

debug.SetMemoryLimit


Go 1.19引入了debug.SetMemoryLimit