Escape Analysis in Go: Stack or Heap? - YouTube
Comments
Transcript
Before we talk about escape analysis, let's take a quick look at the goroutine stack. Every goroutine has its own stack in the application memory.
Here are two goroutines, seven and twelve. Goroutine twelve runs this snippet: the serve function calls the handle function.
This pattern is very common in server and backend code. When the serve function starts, it gets a stack frame on goroutine twelve's stack.
That frame holds serve's local variables such as connection here.
Then serve calls handle, so the handle function also gets its own frame right below,
with its own local variables. That's what a stack frame is: the piece of the stack that one function call gets unless it gets inlined,
but that is another story. When the handle call returns, its frame is popped off the stack,
and that memory can be reused by the next function call.
Serve keeps running with its own frame. Goroutine seven does the same thing, but on its own stack.
Now we're ready for the main story. Here we have the returnPointer function and the main function. The main function calls the returnPointer function, which does what its name says:
it creates a local integer x and returns the address of x.
Then the main function keeps that address in its pointer variable p.
Let's draw this on the goroutine stack we just discussed.
In the diagram, the frame for main has room for its pointer p,
and the frame for returnPointer holds x with the value 42.
Both frames are on the same goroutine stack. At this point, we are in the returnPointer function and p in the main function doesn't have the returned address yet.
After the returnPointer function returns the address of its local x variable,
its frame is popped off, and the next function call can reuse that memory.
The problem is that p still holds an address that points into it.
So when main reads the value that p is pointing to, it's reading memory that doesn't belong to x anymore.
The bytes might still say 42, but any other function call could reuse that space and write over them,
and then main would read the wrong value. So Go needs to put x somewhere that's still there even after the returnPointer function returns, so main can keep reading it.
And that place is the heap. Let's run it again. This time, we allocate the variable x on the heap. returnPointer puts 42 in a slot on the heap,
and returns its address to main. Now returnPointer's frame is gone, but x is still on the heap.
So main can still read 42 through p. When the program can not reach the variable x anymore, the garbage collector frees that slot, and that memory can be used again. But how does Go know that it should put x on the heap?
Escape analysis is the part of the compiler that looks at how pointers are used and decides whether a value,
like a local variable, can stay on the stack or has to go to the heap.
In the returnPointer function, the compiler sees that the address of x is still used after the function returns,
so x escapes to the heap. When we say x escapes to the heap, that doesn't mean x starts on the stack and moves to the heap later.
Instead, x is put on the heap right from the start. That's because escape analysis happens when we build the program, not when it runs.
Now what if the main function passes the address of the variable x
to another function called receivePointer, which then prints the value of x?
The call to the receivePointer function copies the address of x into the parameter p, here. When the receivePointer function dereferences p, it gets the integer that lives in main, so it prints 42. When receivePointer returns, its frame is done, but the frame of main is still there and still holds the x variable.
The receivePointer function doesn't make the address of x outlive the function that created it, I mean the main function.
So x can stay on the stack safely. So how can we know for sure whether the variable x escapes?
The answer can change from one Go version to the next as the compiler gets smarter,
but we can just ask the compiler directly. Let's try it on the receivePointer function, where main creates x and passes the address of x to receivePointer.
We build this program with -gcflags, which passes flags to the Go compiler.
-m tells it to print the choices it made, like inlining and escape analysis.
But here we care about escape analysis only. Each message in the output starts with the file, line, and column.
Line 4, column 21 points to the parameter p in receivePointer function.
The message p does not escape means receivePointer doesn't keep the pointer
or hand it to anything that uses it after the call.
It just dereferences p, prints the number, and that's it.
Now let's run the same command on the returnPointer function.
Here's what we get this time. This one is the decision for the variable x. It's moved to the heap. To see why the compiler put the variable x on the heap,
we can ask for more detail with -m=2. The first line says x escapes to the heap in returnPointer.
All the lines here are line 5, column 2, which points to where x is declared and set to 42, so this report is about that integer. The next line shows where a value flows: the address of the variable x goes into ~r0. But what's that variable? We never declared anything called ~r0. Behind the scenes, the compiler gives every unnamed result of a function an internal name.
In the returnPointer function, the only result has no name,
so the compiler calls it ~r0. If a function had two unnamed results, the second one would be ~r1.
And if we name the result ourselves, the compiler uses our name.
But that's a side story. Let's go back to the version without a name.
So the flow into ~r0 tells us that the function's first return value gets the address of the variable x.
The next line is where we take the address of x, and the line after that is where we return it as ~r0.
The report ends with the final decision: x is moved to heap.
This line is the same one we saw with just -m. Before we look at more examples, I want to go over two safety rules and two limits the compiler has,
and they will explain most of the cases. The first rule is that a pointer to something on the stack can not live longer than that thing,
and this is what we've been talking about so far.
And rule 2: the heap can not hold a pointer to something on the stack.
But why? There are two reasons. An object on the stack has a very short lifetime compared to objects on the heap,
most of the time, right? and its stack frame can be freed, then the pointer in the heap would point to an invalid memory slot.
In addition to that, a goroutine's stack can grow, and when it grows, the Go runtime allocates a new, bigger goroutine stack and then moves everything into the new stack.
The heap can be huge, and fixing every heap pointer pointing to the stack would be way too slow.
And a quick fun fact: Go does fix the pointers inside the stack itself.
We can understand rule 2 with the same returnPointer function,
but let's change this function a bit. This time we have one new variable: y holds the address of x.
Then we return the address of y, so the return type is a double pointer: a pointer to y, which points to x.
If this is a little bit confusing to you because double pointers are rare,
take a quick pause before continuing. Now the report has two decisions. The first one says the address of y goes into ~r0, the result.
The second one says the address of x goes into y.
And both x and y are moved to the heap. Now let's go back to our goroutine stack and heap. The variable y is determined to be heap allocated to avoid breaking rule 1, as we already know.
But it is pointing to x, and according to rule 2, a heap object like this variable y can not point to a stack object, right?
Then x must be heap allocated as well. And that's how main can still reach x, by dereferencing p twice.
But even when a value follows both rules, it may still not be allocated on the stack, because the compiler has two limits.
The first limit is that the compiler can not always tell if a value follows the rules or not. When it's not sure, it picks the heap to be safe.
This leads us to another interesting way to make a variable escape:
storing its address in a global variable. A global variable is declared outside any function, so it lives for the entire lifetime of your application,
at a fixed address that is set up when your binary is loaded into memory.
Here we can modify our receivePointer function a bit. Previously, this didn't make x escape even though we passed the address of x into this receivePointer function.
Literally, x can not outlive main. But what if, instead of printing it, we store the x address in the global variable here? The global lives longer than any function call in our application.
So when these functions return, x must still be reachable from the global variable.
That means x must be allocated on the heap. Quite easy to understand now. Let's confirm it with the escape analysis. The -m=2 report shows us something new. Here we see that x is moved to heap, and that's the final result.
What leads to this result is that parameter p leaks to heap.
Not escapes to heap, not moved to heap, but leaks to heap. That means the parameter p will leak the pointer it holds to the heap,
but not the parameter p itself, as it still stays in the stack frame of the receivePointer function.
The compiler writes all this down as a note about p, and later,
when the compiler looks at the call to the receivePointer function in main, it uses that note.
Then the report says x escapes to heap in main. The flow line says the address of x goes into heap in curly braces,
which means somewhere that can hold on to it after the function returns.
In this case, it's somewhere in memory where Go loads global variables.
The last line of that flow shows where: the call to the receivePointer function.
The pointer going into p is the address of x, so x has to go to the heap. And that's all. But what if we set global back to nil before the function returns?
So by the end of this function, global doesn't hold the address of x anymore.
The output still says x escapes. That means escape analysis sees that global gets the address of x,
and setting global to nil later doesn't undo it.
There are two reasons. The first reason is that Go's escape analysis is mostly flow-insensitive.
It doesn't follow the order of the lines. The second reason is that even if escape analysis were smart enough,
undoing it still wouldn't be safe. Another goroutine could read the global variable right in between those two lines,
while it still points to x, and save the address of x somewhere else and use it later.
Now we have another example for this limitation of Go.
This time let's use a new interface called Printer. The printNumber function takes a Printer interface, creates a local variable x,
and calls the Print method of the Printer interface with the address of x.
Does the compiler know the implementation of printer.Print? Or more directly,
does the compiler know what the printer.Print method will use the address of x for?
In most cases, unless there is an optimization, the compiler doesn't know which type is behind the Printer interface.
The Print method here could save the address of x in a global variable like the previous example
and keep that address valid for a long time. Since the compiler can not tell, according to the first limit,
it plays it safe and puts x on the heap. Let's confirm this with the static analysis. It says that printer.Print is the reason for x being allocated on the heap or moved to the heap.
But there's another interesting message here, leaking param printer.
We know leaking param shows up when a parameter's value can live longer than the function, right?
But printNumber never stores printer anywhere. So why is it leaking?
That's because a method call works like a function call
with the receiver passed as the first argument. So printer.Print with the address of x is the same as calling the Print method of the Printer type, with printer as the first argument and the address of x as the second.
And behind the scenes, an interface is actually a struct that contains two pointers.
The first pointer is not important, but the second pointer points to the value of the concrete type
that implements Printer that we put in this interface. It could be a pointer to struct console, for example. And again, the compiler doesn't know what we will do after unboxing the interface to get that pointer. So, it plays it safe one more time and says printer leaks,
which means the value we put in this interface has to go to the heap too.
For example, the main function here passes the address of the console struct to printNumber,
so this console struct variable must be allocated on the heap.
This case is actually easy to run into, for example, printing a local variable's address with fmt.Println.
Here's the -m output. The first message says x is on the heap. The second message is about the ... argument. To call fmt.Println, Go packs our arguments into a small temporary slice of any.
The slice itself doesn't escape, but the pointer inside it points to x, and x does.
It's the same thing we saw in the previous example.
But why does x escape to the heap? This is a little complicated. We don't need to understand every detail of why x escapes to the heap,
but it's an interesting tour of the internals of Go's fmt package.
So let's try to follow the argument of Println to the place
that causes this slice element to escape to the heap.
The element goes from Println to Fprintln, then into doPrintln, to printArg,
and then to handleMethods here, so the argument here is actually the address of our x variable.
Let's assume the argument turns out to be a Formatter. Formatter is an interface, and here we call the Format method of that formatter interface.
This situation is the same as printer calling the Print method,
where the printer param leaks. The formatter calls Format, and the compiler doesn't know what this method will do with the formatter,
more precisely, the pointer to x we box into formatter,
so x gets into the heap for safety. Of course, the address of x in the example doesn't satisfy Formatter,
but escape analysis is static analysis. It analyzes each function only once, for every possible argument.
It analyzed handleMethods and saw that arg is a leaking param, and that's enough.
The same thing can happen with a function value, which is a function stored in a variable that we can call later, like a callback.
Here, callFunction gets a function value in fn and passes the address of x to it,
but we don't know which function the caller gave us. So we can easily guess x must be allocated on the heap.
Again, let's confirm with escape analysis: fn is just a parameter.
It isn't kept anywhere that outlives the function, so it doesn't escape, and x is moved to heap as expected. But this is not the whole story. This time, let's make it more concrete: fn can be either print or printTwice,
depending on the if condition. Does x escape or not? This is a question for you.
If you guessed that x goes to the heap, you're right,
at least before Go 1.27. Here is the escape analysis result with just -m: two p does not escape lines, one for print and one for printTwice,
and a moved to heap message for x, because the compiler just thinks fn is an unknown function and plays it safe.
But Go 1.27 adds an optimization here. When fn only gets known functions, like here, the compiler can now check every function fn might call, and both of them simply read the integer that p is pointing to,
and that doesn't make x live longer. So x stays on the stack. If at least one of those functions leaks its p param, such as storing p in a global variable in print, our favorite trick by now,
then x goes to the heap. Here is the escape analysis result: printTwice doesn't leak p, but print does,
through its parameter p, so the variable x goes to the heap. Now for the second limit: size. A value that's too big escapes to the heap, even if it's only used inside the function. But how big is too big? Let's try it with two functions: one has an array of 128 kilobytes and the other has a slice of 64 kilobytes.
We'll see why we picked these numbers in a minute. Here's the escape analysis output. The array gets no message at all, because there's nothing to move.
And the message make 64 kilobytes slice does not escape means those 64 kilobytes stay on the stack too, like the array.
Behind the scenes, a slice is a struct with three things: the pointer to the array,
the length and the capacity. Make gives us a slice and a backing array. The compiler just puts the backing array in the stack frame, as a hidden array here,
and points the slice's pointer to it. Neither function allocates anything on the heap. Now let's add just one more byte to each example here,
and look at the escape analysis. One more byte, and both go to the heap. The lines that say too large for stack tell us why. Nothing uses buf after either function returns. It's just too big. When we define a known-length slice or array, Go has two size limits.
If the memory is a variable we declare, like var buf, the limit is 128 kilobytes.
If the compiler creates it for us, with make or new, the limit is 64 kilobytes.
So it's not about arrays versus slices. If we create an array by using new with 64 kilobytes plus one byte,
it's still an array, but the compiler creates it for us,
so it gets the 64 kilobyte limit and goes to the heap.
If you are curious about who creates the memory, here are the common cases.
We create it when we declare a variable, with var or with colon equals.
The compiler creates it when we use new, make, ampersand with a literal,
or when we convert a constant string to a byte slice. So in all of these, the compiler knows the size ahead of time.
But what if the size comes from an argument or from a variable that the Go compiler doesn't know? The slice might only be used inside the function, but the compiler can not make room on the stack for every size a caller might pass,
so this case falls under both limits, right? The compiler is not sure about the size. Here, the size of buf comes from the parameter n, and the backing array of the byte slice here will be allocated on the heap.
Let's run it with escape analysis. Wait, what happened? It shows make([]byte, n) does not escape.
So is our assumption wrong? Yes and no. In Go 1.25, there is an optimization: for every make call where the compiler doesn't know the size and the slice doesn't escape, the Go compiler will reserve a small 32-byte array in our function stack frame
and add a check that runs on every call. Roughly, the compiler turns that make call into this. If n is 32 or less, the backing array will be the stack array,
so the slice buffer points to this array. Otherwise, the slice gets a backing array on the heap.
runtime.makeslice is a runtime function to create a slice, just so you know.
Let's make two calls to the same localSlice function here. When we call localSlice with 8, buf points to the stack array,
but its length and capacity are both 8.
When we call it with 33, those 33 bytes don't fit there,
so buf points to a backing array on the heap. The stack array is still there in the frame, but that call doesn't use it.
So the decision relies on the runtime, not on something escape analysis can prove at compile time.
But that's what I said, without any proof, right? We still want to know whether passing 8 to localSlice, or passing 33 to localSlice,
makes a heap allocation or not. We can not prove it at compile time, but that's easy with a benchmark for runtime proof. Here we will benchmark three cases by calling our localSlice function with 8,
32 and 33 bytes. And remember two things for this to be correct: the function has the go:noinline directive to avoid compiler optimization,
and all three calls use the same function, where the compiler said the make call does not escape. Go test with -benchmem shows us the bytes per op, which is how many bytes go to the heap per call, and the allocations per op,
which is how many heap allocations happen per call. With 8 and 32 bytes, nothing goes to the heap as we expect.
33 bytes don't fit in the stack array, so that call goes through runtime.makeslice.
But we see here the bytes per operation is not 33,
it's 48. That's because for small objects, Go does not allocate arbitrary sizes,
it allocates based on predefined, fixed size classes,
8, 16, 24, 32, 48, 64, 80, and so on.
So the allocator rounds 33 up to 48 bytes, which is why we see 48 instead of 33.
So we already know the rules and the limits. Before we wrap up, let's go through a few more cases to lock that knowledge in.
We will only use -m analysis here, as we only need the conclusion.
First, closures. If a closure captures a local variable and changes it, and we return that closure,
that variable will be allocated on the heap because it outlives the function that created it. Next, goroutines. If we pass the address of a variable to a new goroutine, that variable goes to the heap,
because the goroutine can still be running after the function returns.
Now for channels, if we send the address of a variable on a channel,
that variable goes to the heap, because whoever receives it can use it after the function returns.
How about maps and slices? If we put the address of a variable in a map, or append it to a slice,
that variable goes to the heap. That's because the elements don't live inside the slice or the map variable itself.
A slice only holds a pointer to its backing array, and a map keeps its elements in memory that the runtime manages.
We have a video about how maps work internally already.
The compiler does not follow each element inside a map or a slice, so it plays it safe again.
Next, loops. A variable inside a loop is created again on every iteration.
If we take its address and store it in a variable outside the loop,
the variable inside the loop goes to the heap, because the stack frame only has room for one x, and the next iteration would write a new x over the one we still point to.
And last, interfaces. Here we don't take any address, we only return x as an interface.
But an interface doesn't hold the value itself, it holds a pointer to the value. So because we return it, Go has to make a copy of x on the heap, and the interface points to that copy. Interfaces actually have many exceptions, and we will go into that in the next video. Every heap allocation costs something. The allocator has to find memory now, and the garbage collector has to clean it up later.
So fewer heap allocations can make our code faster.
Of course, don't guess. Benchmark it with the real inputs of your application.
And that's it. You have now mastered escape analysis in Go. See you in the next video.





