Five Things That Make Go Fast (3/5): Garbage Collection

Garbage collection

Mandatory garbage collection makes Go a simpler and safer language. This does not imply that garbage collection makes Go slow, or that garbage collection is the ultimate arbiter of the speed of your program. What it does mean is memory allocated on the heap comes at a cost. It is a debt that costs CPU time every time the GC runs until that memory is freed.

There is however another place to allocate memory, and that is the stack.


Unlike C, which forces you to choose if a value will be stored on the heap, via malloc, or on the stack, by declaring it inside the scope of the function, Go implements an optimisation called escape analysis.


Escape analysis determines whether any references to a value escape the function in which the value is declared. If no references escape, the value may be safely stored on the stack. Values stored on the stack do not need to be allocated or freed. Lets look at some examples:


Sum adds the numbers between 1 and 100 and returns the result. This is a rather unusual way to do this, but it illustrates how Escape Analysis works.

Because the numbers slice is only referenced inside Sum , the compiler will arrange to store the 100 integers for that slice on the stack, rather than the heap. There is no need to garbage collect numbers , it is automatically freed when Sum returns.


This second example is also a little contrived. In CenterCursor we create a new Cursor and store a pointer to it in c . Then we pass c to the Center() function which moves the Cursor to the center of the screen. Then finally we print the X and Y locations of that Cursor . Even though c was allocated with the new function, it will not be stored on the heap, because no reference c escapes the CenterCursor function.

Go’s optimisations are always enabled by default. You can see the compiler’s escape analysis and inlining decisions with the -gcflags=-m switch.


Because escape analysis is performed at compile time, not run time, stack allocation will always be faster than heap allocation, no matter how efficient your garbage collector is.

I will talk more about the stack in the remaining sections of this talk.


原文链接 发表于2014/06/07