← Workshop home / Exercise 11
EXERCISE 11

Slices & Maps — Explosive Growth

Change the slice growth factor to 10x and make maps rehash obsessively.

Exercise 11: Explosive Growth - Slice and Map Internals

Want to learn more? Read Slices, Maps, and Channels on Internals for Interns for a deep dive into how Go’s built-in data structures work internally.

In this exercise, you’ll modify Go’s slice growth algorithm to allocate 10x the needed capacity, and change the map load factor so maps rehash far more aggressively. You’ll see how both data structures manage memory internally and what happens when those management decisions go wrong.

Learning Objectives

By the end of this exercise, you will:

  • Understand the 3-word slice header and how growslice manages capacity
  • Know how Go’s map is structured, including groups and load factor
  • Modify nextslicecap to use 10x growth instead of ~2x
  • Modify the map load factor to trigger more frequent rehashing
  • Observe the memory and performance implications of both changes

Introduction: Slice Internals

Every Go slice is a 3-word header in memory:

type slice struct {
    array unsafe.Pointer  // pointer to backing array
    len   int             // number of elements
    cap   int             // capacity of backing array
}

When you append to a slice and len == cap, the runtime calls growslice to allocate a new, larger backing array and copy the existing elements. The growth formula in Go 1.18+ is roughly:

  • For small slices (< 256 elements): new cap ≈ 2× old cap
  • For larger slices: gradually trends toward 1.25× old cap
  • The formula smooths between these extremes based on the current capacity

This design balances two concerns: - Amortized cost: By doubling, the average number of copies per element is O(1) - Memory efficiency: Not wasting too much for large slices

We’ll change the growth multiplier to 10x, making every append that needs to grow massively over-allocate.

Introduction: Map Internals

Go 1.26’s map is implemented as a Swiss table — a hash table with open addressing and SIMD-friendly control bytes. The key types live in internal/runtime/maps/:

Map:
  dirPtr    pointer    // pointer to directory (array of *table, or inline group)
  dirLen    int        // number of directory entries
  ...

table:
  used      uint16     // number of filled slots
  capacity  uint16     // total number of slots
  groups    groupsReference  // array of groups

group (one group = abi.MapGroupSlots = 8 slots):
  ctrls  ctrlGroup    // 8 control bytes (one per slot): empty/deleted/H2-of-hash
  slots  [8]slot      // 8 key/value pairs

Each group holds exactly 8 key-value pairs. The load factor (maxAvgGroupLoad) controls how full the average group can get before the table grows. The default is 7 out of 8 slots (87.5% full).

We’ll lower it so tables grow when they’re only 50% full — triggering more frequent rehashing.

Step 1: Observe Normal Slice Growth

Create slice_growth.go to see current capacity jumps:

package main

import "fmt"

func main() {
	var s []int
	prevCap := 0

	for i := 0; i < 2000; i++ {
		s = append(s, i)
		if cap(s) != prevCap {
			fmt.Printf("len=%4d  cap=%4d  (grew from %d)\n", len(s), cap(s), prevCap)
			prevCap = cap(s)
		}
	}
}

Run with standard Go:

go run slice_growth.go

Expected output (approximately):

len=   1  cap=   4  (grew from 0)
len=   5  cap=   8  (grew from 4)
len=   9  cap=  16  (grew from 8)
len=  17  cap=  32  (grew from 16)
len=  33  cap=  64  (grew from 32)
len=  65  cap= 128  (grew from 64)
len= 129  cap= 256  (grew from 128)
len= 257  cap= 512  (grew from 256)
len= 513  cap= 848  (grew from 512)
len= 849  cap=1280  (grew from 848)
len=1281  cap=1792  (grew from 1280)
len=1793  cap=2560  (grew from 1792)

Notice: the first allocation starts at cap=4 (the compiler synthesizes a small initial array), then small slices double, and the growth rate smoothly slows down as the slice grows.

Step 2: Find nextslicecap

grep -n "func nextslicecap\|func growslice" go/src/runtime/slice.go

You’ll find that growslice (around line 178) immediately delegates its capacity decision to nextslicecap:

newcap := nextslicecap(newLen, oldCap)

The actual growth logic lives entirely in nextslicecap (around line 326). Inside it, the new capacity is calculated starting from the requested length:

func nextslicecap(newLen, oldCap int) int {
    newcap := oldCap
    doublecap := newcap + newcap
    if newLen > doublecap {
        return newLen
    }

    const threshold = 256
    if oldCap < threshold {
        return doublecap
    }
    for {
        // Transition from growing 2x for small slices
        // to growing 1.25x for large slices.
        newcap += (newcap + 3*threshold) >> 2
        if uint(newcap) >= uint(newLen) {
            break
        }
    }
    ...
}

Step 3: Change Slice Growth to 10x

Edit go/src/runtime/slice.go:

Find nextslicecap (around line 326) and replace its entire body with the 10x growth formula:

// Original logic:
func nextslicecap(newLen, oldCap int) int {
    newcap := oldCap
    doublecap := newcap + newcap
    if newLen > doublecap {
        return newLen
    }
    const threshold = 256
    if oldCap < threshold {
        return doublecap
    }
    for {
        newcap += (newcap + 3*threshold) >> 2
        if uint(newcap) >= uint(newLen) {
            break
        }
    }
    if newcap <= 0 {
        return newLen
    }
    return newcap
}

// Replace with:
func nextslicecap(newLen, oldCap int) int {
    newcap := newLen * 10
    if newcap < newLen {
        // overflow guard
        newcap = newLen
    }
    return newcap
}

Understanding the Change

  • newLen is the minimum capacity needed (the length after the append)
  • Setting newcap = newLen * 10 means we always request 10x the minimum needed
  • After the roundupsize rounding applied in growslice, the actual capacity will be close to but not exactly 10x (see the expected output below)
  • Memory usage will be roughly 6–10x higher than necessary

Step 4: Rebuild the Go Toolchain

cd go/src
./make.bash

Step 5: Observe Explosive Slice Growth

Run the same slice_growth.go with your modified Go:

../go/bin/go run slice_growth.go

Expected output:

len=   1  cap=   4  (grew from 0)
len=   5  cap=  52  (grew from 4)
len=  53  cap= 608  (grew from 52)
len= 609  cap=6144  (grew from 608)

Only 4 growth events for 2000 elements! The slice jumps from 4 → 52 → 608 → 6144. The first allocation (cap=4) comes from the compiler’s initial-array optimization and doesn’t go through nextslicecap. After that, each growth is roughly 10x the minimum needed — with the exact value rounded up by the memory allocator’s size classes.

Memory Impact

package main

import (
	"fmt"
	"runtime"
)

func main() {
	var before, after runtime.MemStats
	runtime.GC()
	runtime.ReadMemStats(&before)

	// Build a slice of 10,000 elements by appending one at a time
	var s []int
	for i := 0; i < 10_000; i++ {
		s = append(s, i)
	}

	runtime.GC()
	runtime.ReadMemStats(&after)

	fmt.Printf("Slice len: %d, cap: %d\n", len(s), cap(s))
	fmt.Printf("Heap allocations: %d KB\n", (after.TotalAlloc-before.TotalAlloc)/1024)
	fmt.Printf("Wasted capacity: %d elements (%dx actual need)\n",
		cap(s)-len(s), cap(s)/len(s))
}
../go/bin/go run slice_memory.go

Expected output:

Slice len: 10000, cap: 62464
Heap allocations: 541 KB
Wasted capacity: 52464 elements (6x actual need)

The slice has 62,464 allocated slots while only using 10,000. The capacity is not exactly 100,000 because growslice passes nextslicecap’s result through roundupsize, which rounds up to the nearest memory allocator size class.

Step 6: Observe Normal Map Behavior

Now let’s look at the map side. Create map_growth.go:

package main

import (
	"fmt"
	"runtime"
)

func main() {
	var before, after runtime.MemStats
	runtime.GC()
	runtime.ReadMemStats(&before)

	m := make(map[int]int)
	for i := 0; i < 10_000; i++ {
		m[i] = i
	}

	runtime.GC()
	runtime.ReadMemStats(&after)

	fmt.Printf("Map size: %d entries\n", len(m))
	fmt.Printf("Heap allocated: %d KB\n", (after.TotalAlloc-before.TotalAlloc)/1024)
}

Run with standard Go:

go run map_growth.go

Expected output (approximately):

Map size: 10000 entries
Heap allocated: 582 KB

Step 7: Find the Map Load Factor

grep -n "maxAvgGroupLoad" go/src/internal/runtime/maps/group.go

You’ll find the load factor constant near the top of group.go:

const (
    // Maximum load factor prior to growing.
    //
    // 7/8 is the same load factor used by Abseil, but Abseil defaults to
    // 16 slots per group, so they get two empty slots vs our one empty
    // slot.
    maxAvgGroupLoad = 7
    ...
)

This controls the growth condition in table.go: a table grows when the number of used slots exceeds (capacity * maxAvgGroupLoad) / abi.MapGroupSlots. With maxAvgGroupLoad = 7 and MapGroupSlots = 8, that’s 87.5% full before growth triggers.

Note: You may notice loadFactorNum and loadFactorDen constants in runtime/map.go. Those are dead code from the old hmap/bmap map implementation — their comment says “used by tests but not the actual map”. Go 1.26 uses a new Swiss table implementation in internal/runtime/maps/. The real load factor to modify is maxAvgGroupLoad in group.go.

Step 8: Change the Map Load Factor

Edit go/src/internal/runtime/maps/group.go:

Change the load factor to trigger growth when the table is only 50% full. The default is 7⁄8 = 87.5% full. To get 4⁄8 = 50% full:

// Original: ~87.5% full before growing
maxAvgGroupLoad = 7

// Change to: 50% full before growing — more frequent rehashing
maxAvgGroupLoad = 4

Important: Values below 4 cause a panic during the build. When the map transitions from its initial inline-group storage (which can hold up to 7 entries) into a table, the new table must have room for all 7 existing entries. A table with capacity 16 and maxAvgGroupLoad = 4 allows (16 * 4) / 8 = 8 entries, which fits. With maxAvgGroupLoad = 3 or lower, the table can’t hold all 7 entries and panics with "invariant failed: growthLeft is unexpectedly 0".

Step 9: Rebuild Again

cd go/src
./make.bash

Step 10: Observe Map Overhead

Run map_growth.go again with your modified Go:

../go/bin/go run map_growth.go

Expected output (approximately):

Map size: 10000 entries
Heap allocated: 1154 KB

The heap allocations roughly double because the map grows twice as often, allocating a new, double-sized group array and rehashing all entries each time.

Understanding the Combined Impact

The two modifications illuminate two different kinds of “waste”:

Change Effect Real-world analogy
Slice 10x growth ~6x memory per slice, far fewer allocations Buy a van when you need a bicycle
Map low load factor Double rehashing frequency, more allocations Rebuild your house every time you add a book

The default slice growth (~2x) and map load factor (7⁄8 = 87.5%) are carefully tuned to balance: - Amortized O(1) insertions (avoid too-frequent reallocations) - Memory efficiency (avoid too much wasted space)

Cleanup

To restore normal slice and map behavior:

cd go/src/runtime
git checkout slice.go
cd ../internal/runtime/maps
git checkout group.go
cd ../../..
./make.bash

Summary

You’ve made Go’s fundamental data structures behave unreasonably:

Slice before: ~2x growth → 12 reallocations for 2000 appends
Slice after:  10x growth →  4 reallocations, but ~6x wasted memory

Map before:  load factor 7/8 → grows when 87.5% full
Map after:   load factor 4/8 → grows when 50% full → ~2x more heap allocation

Changes: runtime/slice.go (nextslicecap function)
         internal/runtime/maps/group.go (maxAvgGroupLoad constant)
Result:  Memory explodes, performance degrades, internals become visible

Continue to Exercise 12 or return to the main workshop

← Previous
Garbage Collector — Anxious GC
Next →
Channels & Select — Predictable Select