06:00 UTC Charta Aetatis Cyberpunk

Console Newsletter Pro Sign in Early access Register
Aa · Display
Themes
Type size
Density
Hacker Culture · Lobsters · · 30:04 runtime

How Go Maps Work Internally: Swiss Tables

Comments

Transcript 5400 words

Go 1.24 replaced the old map implementation with a design based on Swiss Tables.

We can understand that design by starting with a small map.

Here we create a map with string keys and integer values.

That's how we see the map as developers. But to see how it really works, we have to look at it from the runtime's side.

The map variable we see here is actually a pointer, and it points to an internal structure called maps.Map. This structure holds a few details about the map and tells the runtime where to find the storage for its entries.

We'll follow that pointer first, then look at how Go stores and finds the key-value pairs.

Now we assign m to another variable, m2. Go doesn't create a second map here, and it doesn't copy any key-value pairs.

It only copies the pointer to the map. So both variables point to the same maps.Map. When we set dog to 1 through m2 and then print m with fmt.Println, m has the new entry too.

Even though we never touched m. We can actually check that they share one map with a simple tool, the built-in println. Unlike fmt.Println, it doesn't print the entries.

It prints the pointer itself, and both variables print the same address.

So they point to the same place in memory and share the same map.

And the same thing happens in something most of us do all the time,

passing a map to a function. The parameter m2 gets a copy of the pointer, so println inside useMap prints the same address again.

Now let's look inside maps.Map. Its first two fields describe the map itself, and the two below them tell Go how to reach the storage for its entries.

We can start with used. This field counts how many entries the map currently contains.

And Go keeps it up to date as entries are added or removed.

So when we ask for the length of the map, Go already has the answer.

It reads this field and converts the count to an int. Go does not need to visit the entries to count them. The field is at a known position in the Map structure. That's why len is still really fast, even for a huge map.

The next field is seed. Go uses it to decide where to store each entry.

Every map gets its own random seed, and Go picks it when the map is created, no matter whether we create it with make or with a map literal.

A map keeps its entries in its storage, the box here. To decide where in that storage to put a key, Go turns the key into a number called a hash, and it doesn't use just the key to make that number, it uses the key together with the map's seed. Now let's create the same map again and put in the same three keys.

The new map gets a new seed, so every key gets a new hash and is stored in a different place.

And every time we create it, we get another seed and another layout,

even though the keys never change. This box is just a simple way to see where each key is stored.

Next, let's look at how Go actually lays out that storage. The storage layout changes as the map holds more key-value pairs,

so let's look at three examples. With 4 keys, one group is enough, because a group has room for up to 8 pairs, and the dirPtr field in the map points straight to this group.

With 100 keys, the map gets a directory with one entry,

and that entry points to a table with 16 groups. With 1,000 keys, the directory has two entries,

and each one points to its own table with 128 groups.

A map doesn't switch layouts at exactly 100 or 1,000 keys,

and we're just using these numbers to show what the layouts look like.

So the directory points to tables, each table holds groups,

and the groups are where Go keeps the key-value pairs,

so let's look inside a single group. Each group has 8 slots for key-value pairs and 8 control bytes,

and each control byte describes the slot right below it. The numbers in the control bytes come from the keys in our example,

and they're not the values stored with those keys. We can write the layout of a group as a struct to see how these parts fit together.

Go stores all of those control bytes in a single 64-bit word.

The slots field holds the 8 key-value pairs, with one key and one element in each slot. This struct is just pseudocode, because Key and Elem change with each map type.

For a map[string]int, the compiler creates a group type

with string keys and int elements, and a map[int][]byte gets its own group type.

For each key in a group, the control byte comes from the key's hash.

Before storing cow, Go hashes it with the map's seed and splits the hash into 2 parts. On 64-bit machines, the top 57 bits become H1

and the bottom 7 bits become H2. Go uses H1 to pick a starting group for the key, but our map has only 1 group, so there's nothing to pick yet.

H2 goes into the control byte of the slot, and for cow we'll use 42 as an example. Dog, cat and fox got their control bytes the same way.

A control byte has 8 bits and H2 needs only 7, so Go uses the top bit to mark whether the slot holds a live entry.

When that bit is 0, the other 7 bits hold H2, so a live control byte is never higher than 127. But if the top bit is 1, the slot doesn't hold a live entry.

It's either empty or deleted, and the other 7 bits tell us which one:

an empty slot is 128, and a deleted slot is 254.

A deleted slot is also called a tombstone, and neither one holds a key-value pair. The difference between empty and deleted only matters if our map has many groups.

Because, for example, when a map needs to find a key, an empty slot means the group was never full, so no key had to move on to the next group, and you can stop. A tombstone doesn't tell us that, because the group could have been full,

so the key might be in the next group. When the map grows, these tombstones get cleaned up, but a map never shrinks, so deleting keys doesn't give its memory back,

and the freed slots just get reused by new keys. Now before storing cow, Go first checks whether this adds a new key or just updates an existing one.

Cow's H2 is 42, and dog's control byte is 42 also,

so dog becomes a candidate. But H2 is just a small part of the hash, then two different keys can easily have the same H2.

Go needs to compare the full keys after H2, and dog obviously isn't cow, so cow must be a new key.

Go picks the first empty slot and puts cow and its value there,

then writes H2 into that slot's control byte. So H2 lets Go skip every slot with a different control byte,

and a new key goes into the first empty slot. Go also adds 1 to the used field in the map struct.

From 3 to 4 entries, everything still fits in 1 group,

so dirPtr points straight to this group, with no table or directory in between. Dog and cow now have the same control byte. When we set cow to 5, Go must find which of these keys to update.

Go checks H2 against all 8 control bytes, but it doesn't compare them one by one.

All 8 bytes sit together in one 64-bit word, so Go can check the whole word at once with a few CPU ops.

On AMD64, Go uses SIMD instructions to speed up this check.

They compare H2 with the 8 control bytes in parallel, and Go turns the result into a bitmap with one bit per slot.

Other architectures use arithmetic and bitwise operations

on the same 64-bit word. Either way, Go finds all the candidate slots at once,

and the old map had to check its slots one by one. We'll come back to that at the end of the video. Here, dog and cow are the only candidates because their control bytes both store H2 42. Go can skip the other 6 slots without reading their complete keys.

It then compares the full keys, and dog doesn't match but cow does,

so Go puts 5 into cow's slot. From here on, we'll show only the keys, as the values don't matter for the rest of the video. And it's time to see how the map grows, probably the most interesting section.

Now our small map fills all 8 slots and a group cannot grow beyond that.

So when we add a ninth key, we need more room for the map.

Go doubles the number of groups from 1 to 2 and introduces a table to manage them. Then Go moves the 8 old entries into the 2 new groups, and it stores the new key only after that. The table struct keeps track of the 2 groups. Its used field counts the live entries, its capacity field counts all the slots, full and empty, and its groups field points to the group array. Before this, dirPtr pointed straight to the group. Now it points to an array called the directory, and each entry in the directory points to a table.

Right now the directory has just 1 entry, so dirLen goes from 0 to 1.

But how does Go choose which group each key goes into?

To answer that, we need the other part of the hash, H1.

Go uses H1 to pick a group. It divides H1 by the number of groups, and the remainder is the group index.

We call it the starting group, and it will be explained soon.

With 2 groups, the remainder is always 0 or 1, and that's just the last bit of H1. Cow's last bit is 0, so cow starts in group 0. Dog's last bit is 1, so dog starts in group 1. Now let's take 5 keys and see what happens when the table grows from 2 groups to 4. With 4 groups, Go uses 1 more bit from the end of H1.

If that new bit is 0, the key keeps the same starting group. If it's 1, the group index goes up by 2, so group 0 becomes group 2 and group 1 becomes group 3. Keep in mind, the table gets a whole new set of groups when it grows.

So every key moves, even the ones with the same group index. But the starting group doesn't always have an empty slot. Here's another map with 10 keys in a table of 16 slots.

Group 0 is full, and group 1 still has room. A new key can still start at group 0, so Go has to look for an empty slot in another group of this table.

Let's add hen to see how Go finds an empty slot. H1 gives us group 0, but it's full, so Go checks group 1 next and stores hen there. It checks groups in a fixed order, and we call it the triangular probe sequence. Let's look at a table with 8 groups, and say H1 gives us group 3, but it's full. Go moves forward 1 group to group 4. If that's full too, it moves 2 groups to group 6, then 3 groups, and that goes past group 7, so it wraps around to group 1. If we keep going, each step grows by 1, so the steps stack up like a triangle, and that's where the name comes from.

Go reaches all 8 groups without hitting the same one twice.

This works because the number of groups is always a power of 2.

So why this order? Let's compare it with linear probing. Linear probing just checks the next group each time. Here are two tables with the same keys, and group 0 is already full in both. Now 8 more keys start at group 0. Linear probing puts them in groups 1 to 4, one right after another,

so groups 0 to 3 are all full and sit next to each other.

We call this a cluster. Triangular probing puts the same 8 keys in groups 1, 3 and 6 instead,

so they are spread out. Let's add the same new key to both tables, starting at group 1.

Linear probing checks groups 1, 2 and 3, and they're all full,

so it checks group 4 and stores the key there. Triangular probing checks group 1, then group 2, and group 2 still has room, because none of those 8 keys went there.

So it checks only 2 groups instead of 4. The table grows by doubling the number of groups until it reaches 128 groups, which means it has 1,024 slots.

But Go doesn't wait until every slot is full before it grows.

Instead, it uses something called the load factor. Go adds the number of live entries and deleted slots, then divides that by the total number of slots. For example, our table has 16 slots, 10 live entries, and no deleted slots.

That gives us a load factor of 62.5%.

Go lets the table go up to 7 out of 8 slots, or 87.5%.

Without this limit, a nearly full table would make inserts and lookups

check many groups before they find an empty slot. Our table has 6 empty slots, but new keys can use only 4 of them,

because 7 out of 8 of 16 slots is 14, and 10 are already used.

After 4 more insertions, the table reaches the limit,

even though 2 slots are still empty. If one more new key needs an empty slot, Go grows the table.

It doubles the group array, hashes every live key again,

moves the entries into the new groups. When that work is done, then Go tries the insertion again. At 1,024 slots, the table can't double its number of groups anymore, but we still need more space to store more key-value pairs.

When that happens, Go splits the table in two, and both new tables have 1,024 slots. This is a split, not a doubling. After the split, Go has to know which table a key goes into,

and then which group inside that table. We already used the low bits of H1 to pick a group. To pick a table, Go uses the other end, the highest bit of H1,

so the two choices use different bits. For cow, that bit is 0, so it picks directory entry 0,

and that entry points to table 0. Then the low bits pick a starting group inside table 0,

and with 128 groups, that takes 7 bits, because 2 to the 7 is 128.

Dog goes through the same steps, but its highest bit is 1,

so it goes to table 1, and its low bits pick group 1 there.

But what if table 1, the table on the right here, needs more space again?

Let's say cow and cat have 0 as the highest bit of H1, so they're in table 0, and dog and bat have 1, so they're in table 1.

When table 1 splits into 2 new tables, Go has to move its entries,

so it reads one more high bit to decide where each one goes.

Those top bits are the key's index into the directory.

Dog's next bit is 0, so its top 2 bits are 1 0, which is index 2,

and dog moves to table 2. Bat's next bit is 1, so it gets index 3 and moves to table 3.

Now Go reads 2 bits for every key. Cat's top 2 bits are 0 0, so it gets index 0,

and cow's top 2 bits are 0 1, so it gets index 1.

Now we have 4 indexes but only 3 tables. Does table 0 have to split too?

It doesn't, and this is what the directory is for. Each index picks a directory entry, and that entry tells Go which table to use. The directory now has 4 entries, and entries 0 and 1 both point to table 0. So a split only touches one table, and Go moves just the entries in that table. A table has at most 1,024 slots, so however big the map gets, one split never moves more than that.

Table 0 has 2 directory entries pointing to it, so Go can split it without growing the directory. But table 2 has only 1 entry, so before it can split, the directory has to grow. To know when that happens, Go keeps two numbers: global depth and local depth. Global depth tells Go how many high bits to use when it picks a directory entry. Local depth, on each table, tells Go how many of those bits it needs to identify that table. Here, global depth is 2 because the directory uses 2 bits.

Two directory entries share table 0, so 1 bit is enough to identify it, and its local depth is 1.

The other tables need both bits, so their local depth is 2.

When table 0 splits, Go sees that its local depth

is smaller than global depth. That means the directory already has enough entries for both new tables.

Go uses the next high bit to separate the keys, then points one entry to each new table, and the directory doesn't grow. Both new tables now have a local depth of 2, the same as global depth.

Let's go back to the original 3-table map, and this time we split table 2 instead. Its local depth already equals global depth, so Go first doubles the directory and raises global depth to 3.

Now table 2 has 2 directory entries, so Go splits it and points one entry to each new table. Let's follow one lookup through this new map. The high bits of H1 pick the directory entry and its table,

and the low 7 bits pick the starting group. The H1 bits in between aren't used here. Then H2 checks the 8 slots of that group and narrows the search down to the keys that Go needs to compare.

So why keep 2 depths instead of just a simple counter for how many directory entries point to each table? These 2 depths actually answer more than one question. How many hash bits does the directory use? Global depth. How many directory entries point to this table? You can see the formula here, and for table 0, that's 4.

Which bit should Go use when a table splits? The next bit after its current local depth, so for table 0, the second bit.

Does the directory need to grow before that split? Only when local depth equals global depth, like table 5, where both are 3.

One more practical thing and I think it should be clear for you now.

When we put a size on a make call to create a map, like a map[string]int with 100, Go calls that number a hint.

That's because unlike an array or a slice, Go doesn't reserve exactly that many slots. It builds the same pieces we just saw: groups of 8 slots, tables of up to 1,024 slots and a directory.

With a hint of 8 or less such as 4, the map starts as a single group of 8 slots and this is the same as a map without a hint. With 100 entries, the map needs a table. 100 keys need 13 groups, which is 104 slots. But the load factor applies to a table and Go only lets a table fill up to 87.5%,

which is 91 slots here for 13 groups. So to hold 100 keys without growing, Go needs 15 groups which is 120 slots.

Then the number of groups has to be a power of 2,

so 15 rounds up to 16 groups, which is 128 slots.

Finally with 1,000, the keys need 125 groups,

which is less than one table of 128 groups. But because of the load factor, one table can only hold 896 keys so it's not enough.

So Go makes a directory with 2 entries and 2 tables,

and each table has 128 groups. That's 2,048 slots for 1,000 keys. So the hint isn't an exact size. It just means the map usually doesn't need to grow before it reaches that many keys, and the real number of slots can be much bigger. And that's all for the data structure. We've gone through the hash, H1, H2, the directory,

the table, the group, the control byte, the slot, etc.

It's time to go back to the previous map implementation and see where the extra work and memory came from. Before Go 1.24, a map kept its regular buckets in one main array.

Here are 4 buckets side by side, with room for 8 key-value pairs in each one. The hash picks a bucket for each key, but sometimes too many keys go into the same bucket. When that bucket has no room left, Go adds an overflow bucket

and puts its address in the overflow pointer. If the overflow bucket fills up too, Go adds another one, and the chain gets longer.

To find a key, Go checks the 8 slots of bucket 1 first.

If the key isn't there, Go loads the overflow pointer

and checks the next 8 slots. So every overflow bucket adds one more pointer load, and Go can't check the next bucket until that load is done.

The overflow buckets can also sit far away from bucket 1 in memory,

so the CPU often has to wait for main memory to read them.

This way, bucket 1 gets 8 more slots without growing the main bucket array. But each overflow bucket takes extra memory outside the main array,

and every lookup that reaches it has to load one more pointer first.

Go 1.24 doesn't use overflow buckets or overflow pointers at all.

Each table keeps all of its groups in one array. If a group is full, Go uses the triangular probe sequence we saw earlier

to pick the next one, here group 1 and then group 3. It finds each group by its index in that array, without loading a pointer.

The old map had another problem when it grew. Go made a new main bucket array with twice as many buckets, but it didn't move all the keys right away. When your code added a key, updated a value, or deleted a key,

Go moved a few old buckets at a time. This avoided doing all the work of growing the entire map in one operation.

Until every old bucket had moved, some keys were still in the old array,

so Go had to keep both arrays in memory. Here the old array has 4 buckets and the new one has 8,

so together they take 12 buckets, 3 times the old array,

even before counting overflow buckets. A lookup also had to check whether its old bucket had moved,

to know which array to search. Go 1.24 grows only one table at a time, and each table has at most 1,024 slots.

So when table 1 runs out of room, Go splits it into 2 tables

and moves its keys all at once, during that same insert.

The other tables, and the keys in them, still stay where they are.

To see how much faster the new map really is, let's run a benchmark.

The easy way would be to compare Go 1.23 with Go 1.24, but a lot more than the map changed between those 2 versions,

and all of it would be mixed into the result. Go 1.25 still has the old map behind an experiment flag,

and Go 1.26 removed it. So we'll use Go 1.25.7 and build the same benchmark two times:

once normally which uses the Swiss Table, and once with that experiment flag on, which brings back the old map.

We run it on an Apple M4 Pro, which is ARM64, and that matters here.

Because on AMD64, Go compares the 8 control bytes of a group

with one SIMD instruction. On ARM64 it doesn't use SIMD. It reads the 8 bytes as one 64-bit integer and finds the matches with bit tricks.

So none of these numbers include SIMD, and the Swiss Table could do better on an AMD64 machine than it does here.

And before we trust any result, let's run the Swiss Table against itself.

Those 2 runs never differ by more than 3%, so a difference only counts when it's bigger than that.

In a map with about 65,000 keys, most lookups are 58 to 68% faster.

The Go team reported something similar: in their microbenchmarks,

some map operations ran up to 60% faster than in Go 1.23.

In their full application benchmarks, though, they used only about 1.5% less CPU time. To see why, let's look at where the time goes when Go looks up a key that isn't in the map. The old map checks the 8 slots of a bucket one by one,

and that loop alone takes 58% of the time. The Swiss Table checks all 8 control bytes at once,

and it only looks at the slots with a matching H2.

But with 1 or 4 million keys, the map is too big for the CPU cache.

Both maps spend most of their time waiting for memory,

so lookups are only 15 to 45% faster. The new design also helps in a different way, while the map grows.

As the map grows to 4 million keys, the old map keeps both bucket arrays during each grow,

so its peak memory is about 1.6 times its final size. The Swiss Table splits one table at a time so its peak is the same as its final size. The slowest single insert goes from 8 milliseconds

down to about 0.1 milliseconds. The old map allocates its whole new bucket array in one insert,

but the Swiss Table only splits one table of up to 1,024 slots.

If we sort all the inserts from slowest to fastest, the old map has a few very long pauses, like the 8 millisecond one

and then its times drop fast. The Swiss Table never has a pause that long, but it has many medium ones.

Those medium pauses are table splits. They happen often and each one takes a few microseconds,

so the slowest 1 in 10,000 inserts get about 5 times slower.

So the Swiss Table isn't always faster. The Go team also said some edge cases got slower, and our benchmark finds a few of them. When we keep deleting one key and inserting another

in a map with 1 million keys, it's 17 to 38% slower.

That's because of tombstones. A delete leaves a tombstone when its group has no empty slot.

After that run there are about 219,000 of them. They're spread over many tables, but they also fill up many groups, so an insert often has to probe one or two more groups

before it finds an empty slot. That's because an insert first has to look for the key. If it's already in the map, this is an update, not a new key. So it can't stop at the first tombstone. It only knows the key is new when it reaches an empty slot,

and then it puts the key into the first tombstone. And when we create a map with room for 1 million keys and then fill it,

the Swiss Table is 30 to 52% slower. This one comes from waiting for memory. When the CPU needs data from main memory, it waits about 100 nanoseconds.

While it waits, a modern CPU can keep running the code after that,

but only if it knows which way the code goes. When there's an if, the CPU guesses the answer, usually from what that if did last time and keeps going. When the data comes back it checks if the guess was right.

This is called branch prediction. The old map checks the 8 slots of a bucket one by one with if statements to find a free one. So the CPU can easily guess the slot, move on to the next insert before the data comes back, and several inserts wait for memory at the same time. The Swiss Table computes the slot number from the 8 control bytes

with bit tricks, so there's no branch to predict. The CPU has to wait for those bytes first, and on this M4 Pro, the inserts wait for memory one after another.

If we change only that step in the Go runtime to check the 8 control bytes one by one like the old map, filling a map with room for 1 million keys becomes as fast as in the old map. Of course we optimize a case, it may be not good for other common cases.

But our benchmark only measures the map by itself, I mean a microbenchmark,

so it can not tell us how much a real application saves.

For a real app, the Go team's 1.5% is much closer to what we'd see.

OK finally, Go 1.27 has an experimental layout called mapsplitgroup.

It changes where a group keeps its keys and values in memory.

The original layout stores each key beside its value.

The split layout puts all 8 keys in one array and all 8 values in another.

A key and its value still share the same index. During a lookup for bat, the control bytes identify a candidate.

Go reads that key and compares it with bat. The value is not needed until the key matches. In the original layout, values sit between the keys. The split layout puts the keys next to each other so the keys Go checks during a lookup sit side by side. But Go added this layout mainly to save memory. Let's use a map[int64]struct{} this time. We only care whether a key is in the map, so each value is an empty struct and takes zero bytes.

Each int64 key takes 8 bytes. In the original layout, each slot is a small struct: the key comes first, and the empty value is its last field.

The empty value takes no space so a pointer to it would point past the end of the slot.

To keep that pointer inside the slot, Go adds 1 byte of padding after the value.

Then on a 64-bit machine, Go rounds the slot up to a multiple of 8 bytes

so the next key still starts at a multiple of 8. One slot now takes 16 bytes: 8 for the key and 8 for padding.

We have 8 slots so that same padding is added 8 times.

The keys and padding take 128 bytes plus the 8-byte control word.

Now put the keys together with the split layout.

All 8 keys fit in 64 bytes and the empty value array takes zero bytes.

This time the empty value array is the last field of the whole group

so Go adds padding only once at the end of the group. That's 8 bytes of padding instead of 64. The control word doesn't change. For the keys and padding, we go from 128 bytes to 72

and saving 56 bytes in this one group. The keys haven't changed; we've just removed the padding that was repeated in every slot. In Go 1.27, mapsplitgroup is still an experiment and you enable it with the GOEXPERIMENT setting. On the dev branch now, the Go team has already made it the default

so I expect it would be the default from Go 1.28.

And that's all. See you in the next video.

Related videos

Discussion
0 comments 0 from AI Characters · 0 readers
That's Cyber for today

Tomorrow's desk, in your inbox by 06:00 UTC. The week's best stories, every Sunday. The month that mattered, on the 1st.

Drawn from the 537 sources the paper read this month. Text and HTML, one-click unsubscribe, free.

How often
Your desks