Go Empty Interface Explained & The Hidden Heap Allocation
Comments
Transcript
Machine-transcribed by YouTube. Expect errors in names, commands and version numbers.
An empty interface or any as its alias is probably the most interesting type in Go and also one of the trickiest. We use any all the time, but what actually happens when we put a value into it? Is the value copied? Does it cost a heap allocation? Why isn't any holding a nil pointer not? It all comes down to how go stores an any to the gospec. All interfaces either empty interface or non-mpt interface are the same kind of thing. An interface is just a list of methods. Any is an interface with an empty list and IO reader is an interface with one method in its list. That's the only difference.
The runtime doesn't see it that way. It splits interfaces into two kinds with one question. Does the interface have any methods? Interfaces that list types like a tilda int or tilda float 64 constraint are still interfaces in the spec, but go only lets us use them as constraints for generics. We can't declare a variable of that type, so there's never a value of it for the runtime to store and they don't show up here at all. We can print the size of the empty interface on a 64-bit machine. Both any and IO reader take 16 bytes. So from a
developer's point of view, the two kinds are no different. Both are just interfaces. But inside the runtime stores them differently. An empty interface is a strct called eface. And an interface with methods like IO reader is a strct called iface. They both store two pointers. Only the second pointer data is the same in both. We'll start with ephace short for empty interface.
When we assign a value to an empty interface, it needs to know the type of the value and the value itself. The first pointer is for the type and here it points to the type descriptor of Rect. When Go builds the binary, every type the program needs while it runs gets a type descriptor. Both the types we define like rect and built-in ones like int, bool, and string. The linker puts them all in one section just for types.go.type type on Linux and go type with two underscores on Mac OS. We can see that section in our own binary with obj dump-h which lists the sections of a binary. The names are different but it's the same layout. The text section holds our code and the go type section holds all the type descriptors including the one for wctck. When we run the program, the OS loads these sections into the program's memory. So the type descriptors are in memory too. The type word holds the address of the recct descriptor inside the part of memory where the go type section was loaded.
The second pointer data is how an empty interface reaches the value it holds. Let's start with a simple case. We store a wctck in an any variable a and then we change the width of the initial rect to 9. Now we run the snippet. The wctck that the empty interface points to still has two as its width, not nine. So the data word of A doesn't point to the variable R. Internally, Go makes a copy of the value and the data word points to that copy. That's just the general idea. Where it actually points is quite interesting and we'll get to that later. Now what happens when we copy an interface like a two equals a. The variable A is just two pointers. So it copies those two pointers into a two and that's all. Direct isn't copied again and both data words point to it. Sharing like this is safe because the copy is immutable. There's no way to change the wreck through one interface and affect the others. Of course, we can still change it with the unsafe package, but that may crash the program depending on where data points.
Getting the value back out is the opposite. A type assertion to recct reads the fields from where the data word points and copies them into a new rect. So the wreck we get back is another copy. But so far that's just me saying it. Can we actually see these two pointers? We can with a very simple tool that's built into Go. Print line. It doesn't print two and three for an interface. Print line prints the two words themselves. The first one is the type word, the address of the type descriptor of Rect. The second one is data, the address where our WCT is stored. Now that we can see the two words, let's use them to explain a scenario that surprises a lot of beginners. Here we declare an intpointer and set it to nil.
We store it in an empty interface a and then we check if a equals nil or not. The int pointer equals nil and a equals the int pointer. So in turn a equals nil, right? No, it takes this branch and prints a is not nil. If we use fmpt.print print line for A and for another empty interface B that we just declare without assigning anything both print exactly the same thing new this trips up quite a lot of people fMT.print Print line doesn't actually print the interface itself. It prints the value stored inside it. So let's use the more powerful tool print line.
For B, both words are zero. For A, the data word is 02, but the type word is an address, the descriptor of star int. So an interface is nil only when both words are new, the type and the data. A holds a new pointer, but it still has a type, so it isn't new. Knowing how it works internally makes this situation much easier to explain. Behind the scenes, this check depends entirely on the type word. When the type word is new, the data word is always new, too. And if the type word is there, the any isn't new, whatever the data word holds. At this point, we can say the data word points to a copy of the value. But Go doesn't always make that copy the same way and sometimes it doesn't make one at all.
How Go does it depends on three things. The type of the value, whether the compiler already knows the value, and how long the value has to live. We can sort that into four scenarios. Scenario one, the value is a pointer. Here the variable P is a pointer to erect. Then we store P in the empty interface B. In this case, P is already a pointer just like the data word. So instead of making a copy of P and pointing to that copy, the data word holds the value of P directly, which means it points straight to the recct. So if we store a pointer and then change the value behind it, the interface sees the change. But earlier we said the value in an interface is immutable. So why can we change the wctck here?
Immutable means that when we assert it back out, we get the same value we put in here. That value is the pointer, not the rect. Even if we set P to nil, asserting B still gives us the pointer to the rect. Now, storing a pointer like this works the same way for a map, a channel, or a function value. Under the hood, each of them is just a pointer. So, it goes straight into the data word, too. A map in an Annie has the map pointer as its data word, pointing to the internal map structure. I've made a video on how maps work under the hood. So, if you haven't seen it yet, it's a good one to watch after this, but the value doesn't have to be a pointer type. A strruct that holds only one pointer is stored the same way. Here we have a wrapper strct that contains an int pointer. Behind the scenes, an int pointer and a strruct that contains one int pointer look exactly the same. The address of the wrapper and the address of its fieldp are the same, and their size is the same, too. eight bytes on a 64-bit machine. So in this case, we can treat it as a pointer. When we store this wrapper value in an empty interface, the data word uses the pointer value directly and points straight to the int. Only the type word is different. It points to the descriptor of wrapper instead of the descriptor of the int pointer type. The compiler doesn't care whether the type is a strct or an array.
for example, an array with one pointer element or a strruct that contains one map since a map is a pointer behind the scenes. But add one more field and the strruct is no longer just a pointer. So go copies it like any other strct.
Scenario two. The compiler already knows where the value is. There are three cases like that and the first one is a constant. Here we store 1,00 in an empty
interface A. This number is written right in our code. So the compiler already knows it while compiling. So it puts a readonly copy of 1,00 into the binary under a name like STM0. When our program runs, that copy is mapped into memory along with the rest of the binary just like the type descriptors and the data word holds its address there. The assignment compiles to one instruction that just loads the address of that copy. nothing has to run to make the copy and nothing is allocated. It's the same with a strct where every field is a constant like rec 23.
If every field is zero like an empty rect, the compiler doesn't even write a copy. The runtime package already has a place full of zeros. Zero val, a global array of 1,024 bytes, all of them zero. So a zero strruct or array of at most 1,024 bytes just points to zerovall.
The second case is a value of size zero. Some types take zero bytes, an empty strruct, an array of length zero, an array of empty strrus or a strct with fields that are all like that. These values are immutable by nature because they don't have any data for you to change. So go just uses the same address every time. zero base a global variable in the runtime package just eight bytes
we can see both of these global variables in the runtime package zero val is here and zero bases here and it's not only these values every allocation of zero bytes that escapes also gets the address of zero base so all of them point to the same eight bytes
the last case is a bool or a one byte integer like int 8 in 8 or bite these types can only hold 256 6 different values 0 to 255. The runtime package has a global array with all of them. Static U in 64s. It holds 256 numbers and element N holds the number n. Since every value of these types has an element there, the compiler knows from the type alone that it can point there. If we look at the assembly, each line is literally just two instructions. One loads the type and the other loads the address of its element like static u 64s + 8 for true. So an
any holding false points to element zero and an any holding true points to element one. This only works because the copy inside an interface is immutable. Here we take the data word of uh and write through it with unsafe. When we run it, the program crashes with a fatal error. We can also ask the compiler which place it picked. The compiler has a debug flag escape debug that prints one line for every value we put into an interface. Every line says using global. So every value points to something that's already in the binary. Scenario three. Now go doesn't know the value beforehand. Like the int parameter n of this show function. The value could be 1 1,000 or 1 million. The compiler can't predict it. So when we assign that variable to an empty interface, that value must be copied. And in this case, the copy lives in the stack frame of the function. If you don't know why the copy lives in the stack frame of the function or haven't seen how escape analysis works in Go yet, we have a video that explains escape analysis. It's a good one to watch. Now let's confirm it with escape analysis and does not escape. The debug flag shows what the compiler does with that result using stack temporary for interface value n. That means the copy of n goes on the stack in a temporary variable of the function show.
If we look at the assembly, go uses the register r0 for the type word and r1 for the data word of the empty interface a. Then the compiler adds a hidden local variable named autotemp 2. The print line call becomes a call to runtime.print print eface and it receives exactly the two words of a the type int and the address of autotemp 2.
So in this case the pseudo code can look like this. The compiler decides where the copy goes and it reserves a slot on the stack for that temporary variable. In all three scenarios, the compiler is the one who decides the data word points to the memory directly or to a copy in the binary or to a copy in the stack frame of the function. Scenario four, the runtime is the one who decides because the copy escapes. Now, we change the show function here a bit, so it stores n in a global variable instead. This is a trick I use most of the time since it's a short way to make a value escape to the heap. Let's check the escape analysis report. It says n escapes to heap, but that's odd because when a variable escapes, Go usually reports move to heap, not escapes to heap. Go reports move to heap when the variable itself has to live on the heap and that message points to the line where the variable is declared not to the line that makes it escape like the report for the first snippet. That's because the compiler reads global equals n as global equals any of n. So the thing that escapes here isn't n but the conversion. It needs a place to hold a copy of n and that place is what escapes to the heap. If we write the conversion explicitly, the message here is also clearer. In this case, the compiler doesn't reserve a slot on the stack. It needs help from the go runtime. Instead, let's look at the assembly. The assignment to global becomes a call to a function in the runtime package. Runtime conv64.
The name means it converts a 64-bit value. So, what about values of other types? We have convert functions for different types. Int, string, slice, types with no pointers, and others. Here the runtime can optimize however it wants. For example, if we assign a number less than 256, it can use the static UI 64's table we saw earlier and avoid the allocation. Otherwise, comity 64 allocates eight bytes on the heap and copies the value there. So, show seven cost no allocation and show 1,000 cost one. And an empty string or a new slice points to zero val. Any other string or slice gets a copy on the heap. So the escape message doesn't always mean the heap and only the heap copies cost an allocation.
We can see that with both flags at once. Here we store an empty wctck in the global. Escape analysis says it escapes to heap. But the next line says the data word points to zero val. Nothing is allocated. A strruct value that escapes gets a new heap copy on every store whatever it size. Here big is a 128 byt strct. We
store it in a global any and count the allocations. That's one each time. But with a pointer to it, it's zero allocations. For a big value, we store often. Storing a pointer skips that copy and every interface holding that pointer shares the one value. This happens a lot with sync.pool where we keep passing the same object into an interface. If we use a pointer here instead, nothing is copied. Coincidentally, we have a video about that problem if you want to go deeper. How does go compare to any values with each other? It works in two steps. Compare the two type words. If they are equal, compare the values that the data words point to.
Here we have a small function that simply compares two empty interface values with equals. Behind the scenes, what it really does is this pseudo code. The compiler turns the equals b into two checks. The type words are equal and runtime. Equal checks that the values are equal. So if we compare int 7 7 and uint 647 the two type words aren't equal. So it stops right away even though the values look the same. Runtime face equal is the same as an equality check on what the data words point to. But there's an optimization. When we assign a pointer to an empty interface, the data word holds the pointer itself. So it compares the pointers as an exception.
Look at its implementation. Besides checking the data words and the values the data words point to, it also panics when the type is uncomparable. For example, here we have a couple of comparisons and the last one compares two slices, but a slice is considered an uncomparable type in Go. This is the same for a map or a funk. They're uncomparable types in Go, so their equal field in the type descriptor is new.
Once a value is in an Annie, we get it back out with a type assertion. Here's a function get that asserts X to an int. Behind the scenes, what it really does is this pseudo code. The code compares the type word with the descriptor of int. If they differ, it panics. If they match, it copies the int that the data word points to. With okay, the assertion does the same compare. But a wrong type doesn't panic. There's no call to a panic function at all. only the compare that says okay. What comes back depends on the type we assert to. Asserting to rect copies the value out. So we get a new rect. Asserting to a pointer to rect returns the data word itself since a pointer is stored as it is. So we get the same rect back. That's why setting a field through the pointer to rect assertion changes the value inside the interface while the same line with rect doesn't even compile.
A type assertion checks one type, but often we don't know which type is inside an any, and we want to do something different for each one. That's what a type switch is for. Here's a function kind with a type switch of five cases. Each case is a type. Go runs the case that matches the type of the value inside X or the default when none does.
So, how does Go pick the case? The simplest way would be five ifs one after another. But if X holds a bool, Go has to compare the type word with all five types before it finds the case. Go doesn't do that. The compiler turns this switch into a jump table, a small list in the binary where each slot holds the address of the code for one case. To pick a slot, the code uses the hash field of the type descriptor. The compiler already knows the hash of every case. So, it takes three bits of each hash, a number from 0 to 7, one for each slot. It tries bits 0 to two first, then 1 to three, and so on until all five cases get different numbers. For our five types, that's bits 13 to 15. All this happens while compiling. When the program runs, getting the slot is just one shift and one mask. So for a string, the code jumps straight to the string case. But landing in a slot doesn't prove the type. Int 64 also gets slot one, the same as string. So each slot still compares the type word once. And for int 64 that compare fails and kind returns zero. And a neil any has no descriptor to read a hash from. So it goes straight to the default. And this is what the function kind looks like when it compiles. But what if no three bits in a row give every case its own number. Then the compiler tries four bits, a table of 16 slots, and then five bits, a table of 32 slots. If that fails too, it sorts the cases by hash and compares them like a binary search.
Either way, the type word is compared only once. So the order we write concrete cases in doesn't change the speed of a type switch. And that's how an any works under the hood. Two words, one for the type and one for the data. See you in the next video.