在Go语言中,是否可以使用不同的垃圾回收策略?

huangapple go评论85阅读模式
英文:

Is it possible to use different garbage collection policies for Go?

问题

正如标题所说,我想知道是否可以更改Go语言使用的GC策略?

英文:

As the title says, I wonder if it is possible to change the GC policy used by the Go?

答案1

得分: 1

并不是像Java或其他语言那样,你可以完全使用不同的收集器。这是有意为之的;他们希望得到一个在任何地方都能正常工作并避免GC参数调优成为Go程序员专长的东西。

最常用的选项是GOGC。默认值为100,这意味着在上一次GC之后,你的程序可以增长到两倍的活跃数据量之前,触发另一次垃圾回收。如果设置为200,程序可以增长到上一次GC后活跃数据量的3倍,如果设置为50,程序只能增长到上一次GC后活跃数据量的1.5倍。在底层,垃圾回收的确切时机和节奏要复杂一些,因为从1.5版本开始,GC是并发的,但基本思想仍然是以大约两倍的活跃数据量为目标来控制内存的峰值使用。

实际上,我见过GOGC的主要用途是人们将其增加以减少程序的垃圾回收工作量,当他们知道有多余的内存可用时。例如,有人将Go编译器的GOGC设置为400,以稍微提高速度。但请注意,通过消耗大量内存来拖慢服务器的运行远比花费更多的CPU时间进行垃圾回收更加灾难性,所以不要过度使用这个选项。

还有其他一些参数可以在runtime包中找到。使用当前实现,你可以再次强制GC停止整个程序,或者使用runtime.GC()显式触发潜在的停止整个程序的垃圾回收。除了GC参数之外,runtime还允许你使用ReadMemStats来获取内存统计信息和性能分析数据,这些通常非常有用。

通常情况下,你不需要过多关注GC调优的细节;默认值效果很好,你的时间通常更好地花在思考应用程序本身上。

英文:

Not in the sense that you can use entirely different collectors like in Java or so on. This is on purpose; they want to get something that works decently well everywhere and avoid GC parameter tuning becoming a specialty for Go programmers.

The most often used option is GOGC. The default value of 100 essentially lets your program grow to twice the amount of live data it had after the last GC before another collection is triggered. 200 would let the program grow to 3x the live data after last GC, 50 would let it grow to only 1.5x. The exact timing and pacing of the collection is a little more complicated under the hood since 1.5 made GC concurrent, but the idea is still to target peak memory use of ~2x the amount of live data.

Practically speaking, the main use of GOGC I've seen is people increasing it to reduce a program's garbage collection workload when they know they have memory to spare. People have run the Go compiler with GOGC=400 or such for a little speedup, for instance. But note it's far more disastrous to bog down your servers by eating a lot of RAM than to spend a few percent more CPU time GC'ing, so don't go overboard with this.

The other knobs that exist are documented in package runtime. With the current implementation you can force GC's to be stop-the-world again or explicitly trigger potentially-stop-the-world collections with runtime.GC(). Separate from GC knobs, runtime also lets you ReadMemStats and get profiles, which are often useful.

You generally don't want to focus much on the little GC tuning possible; defaults work pretty well and your time is usually better spent thinking about your application.

huangapple
  • 本文由 发表于 2016年11月2日 03:35:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/40367383.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定