Interning values with unique

suggest change

Interning means keeping a single copy of each distinct value and making everybody share it. Programs that load lots of data often see the same small set of strings repeated millions of times: log levels, service names, HTTP header names, country codes, tag keys. Without interning every occurrence is its own allocation.

Go 1.23 added package unique to the standard library. It has one function and one type:

Two handles are equal (==) if and only if the values used to make them are equal. A handle is the size of a pointer, so comparing handles is a single pointer comparison no matter how big the value is.

Unlike a hand-written intern table, unique doesn't keep values alive forever. When no handle for a value exists anymore, the garbage collector removes the value from the internal table.

Basic usage

package main

import (
	"fmt"
	"strings"
	"unique"
)

func main() {
	a := unique.Make("hello world")
	// build the same string at runtime so it's a different allocation
	s := strings.Repeat("hello", 1) + " world"
	b := unique.Make(s)
	c := unique.Make("goodbye")

	fmt.Println("a == b:", a == b)
	fmt.Println("a == c:", a == c)
	fmt.Println("a.Value():", a.Value())
	fmt.Printf("type: %T\n", a)
}
a == b: true
a == c: false
a.Value(): hello world
type: unique.Handle[string]

a and b were made from strings stored in different memory, but they have the same content, so unique.Make returned the same handle. Make is safe to call from many goroutines at once.

A Handle has no String method. fmt.Println(a) prints the internal pointer, something like {0x38c7f6b40070}. Call Value() when you need the string.

Any comparable type works

T can be any comparable type: strings, numbers, arrays, and structs whose fields are comparable.

package main

import (
	"fmt"
	"unique"
	"unsafe"
)

type Location struct {
	Country string
	City    string
}

func main() {
	h1 := unique.Make(Location{"Poland", "Warsaw"})
	h2 := unique.Make(Location{Country: "Poland", City: "Warsaw"})
	h3 := unique.Make(Location{"Poland", "Krakow"})

	fmt.Println("h1 == h2:", h1 == h2)
	fmt.Println("h1 == h3:", h1 == h3)
	fmt.Println("city:", h1.Value().City)

	// handles are comparable, so they work as map keys
	visits := map[unique.Handle[Location]]int{}
	visits[h1]++
	visits[h2]++
	visits[h3]++
	fmt.Println("Warsaw visits:", visits[unique.Make(Location{"Poland", "Warsaw"})])

	fmt.Println("sizeof Location:", unsafe.Sizeof(Location{}))
	fmt.Println("sizeof Handle:  ", unsafe.Sizeof(h1))
}
h1 == h2: true
h1 == h3: false
city: Warsaw
Warsaw visits: 2
sizeof Location: 32
sizeof Handle:   8

Interning a struct as a whole is often better than interning each field. Here one 8-byte handle replaces two string headers (32 bytes), and comparing two locations compares one pointer instead of two strings.

Cheap equality

Comparing two strings means comparing their lengths and then their bytes. Comparing two handles means comparing two pointers. A benchmark with two equal 1 KB strings stored in different memory:

package bench

import (
	"strings"
	"testing"
	"unique"
)

// two equal 1 KB strings in different memory
var (
	s1 = strings.Repeat("a", 1024)
	s2 = strings.Repeat("a", 1024)
	h1 = unique.Make(s1)
	h2 = unique.Make(s2)
)

var sink bool

func BenchmarkCompareStrings(b *testing.B) {
	for b.Loop() {
		sink = s1 == s2
	}
}

func BenchmarkCompareHandles(b *testing.B) {
	for b.Loop() {
		sink = h1 == h2
	}
}

var hsink unique.Handle[string]

func BenchmarkMakeShort(b *testing.B) {
	s := "eu-central-1"
	for b.Loop() {
		hsink = unique.Make(s)
	}
}

func BenchmarkMake1KB(b *testing.B) {
	for b.Loop() {
		hsink = unique.Make(s1)
	}
}
$ go test -bench . -benchmem
BenchmarkCompareStrings-24    	56084462	        19.63 ns/op	       0 B/op	       0 allocs/op
BenchmarkCompareHandles-24    	1000000000	         0.9828 ns/op	       0 B/op	       0 allocs/op
BenchmarkMakeShort-24         	30059968	        43.00 ns/op	       0 B/op	       0 allocs/op
BenchmarkMake1KB-24           	11946693	       109.6 ns/op	       0 B/op	       0 allocs/op

Comparing handles is about 20 times faster here, and the gap grows with the size of the value. But look at Make: it hashes the value and looks it up in a global concurrent map. That costs more than a single string comparison. Interning pays off when you make a handle once and then compare, hash or store it many times. It doesn't pay off if you call unique.Make just before every comparison.

Handles are also cheap map keys. Hashing a Handle hashes a pointer, while hashing a string reads every byte. See Benchmarks for more on writing benchmarks.

Saving memory on repeated strings

The typical use case: parse a large log file and keep the records in memory. The sample has a million lines, but only 4 service names, 3 regions and 3 levels.

package main

import (
	"fmt"
	"runtime"
	"strings"
	"unique"
)

// Event keeps fields as plain strings.
type Event struct {
	Service string
	Region  string
	Level   string
}

// EventH keeps the same fields as handles.
type EventH struct {
	Service unique.Handle[string]
	Region  unique.Handle[string]
	Level   unique.Handle[string]
}

var (
	services = []string{"auth-service", "billing-service", "search-service", "frontend"}
	regions  = []string{"us-east-1", "eu-central-1", "ap-southeast-2"}
	levels   = []string{"INFO", "WARN", "ERROR"}
)

// makeLine simulates reading one line of a log file:
// every line is a new string allocated on the heap.
func makeLine(i int) string {
	return fmt.Sprintf("service=%s region=%s level=%s msg=request handled id=%d",
		services[i%len(services)], regions[i%len(regions)], levels[i%len(levels)], i)
}

func field(line, key string) string {
	for _, kv := range strings.Fields(line) {
		if v, ok := strings.CutPrefix(kv, key+"="); ok {
			return v // a substring: shares memory with line
		}
	}
	return ""
}

func heapMB() float64 {
	runtime.GC()
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	return float64(m.HeapAlloc) / (1 << 20)
}

const n = 1_000_000

func main() {
	base := heapMB()

	events := make([]Event, n)
	for i := range events {
		line := makeLine(i)
		events[i] = Event{field(line, "service"), field(line, "region"), field(line, "level")}
	}
	fmt.Printf("strings: %6.1f MB\n", heapMB()-base)
	runtime.KeepAlive(events)
	events = nil

	base = heapMB()
	events = make([]Event, n)
	for i := range events {
		line := makeLine(i)
		events[i] = Event{
			strings.Clone(field(line, "service")),
			strings.Clone(field(line, "region")),
			strings.Clone(field(line, "level")),
		}
	}
	fmt.Printf("cloned:  %6.1f MB\n", heapMB()-base)
	runtime.KeepAlive(events)
	events = nil

	base = heapMB()
	eventsH := make([]EventH, n)
	for i := range eventsH {
		line := makeLine(i)
		eventsH[i] = EventH{
			unique.Make(field(line, "service")),
			unique.Make(field(line, "region")),
			unique.Make(field(line, "level")),
		}
	}
	fmt.Printf("handles: %6.1f MB\n", heapMB()-base)
	fmt.Println(eventsH[5].Service.Value(), eventsH[5].Region.Value(), eventsH[5].Level.Value())
}
strings:  130.8 MB
cloned:    87.8 MB
handles:   22.9 MB
billing-service ap-southeast-2 ERROR

There are 3 versions:

unique.Make copies a string before storing it the first time (including strings inside structs and arrays), so a handle never keeps the larger string it was sliced from alive. You don't need to call strings.Clone yourself.

Unused values are garbage collected

Before Go 1.23 people wrote interners with a map:

type Interner struct {
	m map[string]string
}

func (in *Interner) Intern(s string) string {
	if v, ok := in.m[s]; ok {
		return v
	}
	in.m[s] = s
	return s
}

This works, but the map only grows. Every string ever interned stays in memory until the whole Interner is dropped. In a long-running server that sees an unbounded set of values (user ids, URLs) this is a leak. You also have to add a mutex to use it from multiple goroutines.

unique holds values weakly. When the last handle for a value becomes unreachable, the runtime removes the entry:

package main

import (
	"fmt"
	"runtime"
	"strconv"
	"time"
	"unique"
)

// Interner is the classic pre-Go 1.23 approach.
type Interner struct {
	m map[string]string
}

func (in *Interner) Intern(s string) string {
	if v, ok := in.m[s]; ok {
		return v
	}
	in.m[s] = s
	return s
}

func heapMB() float64 {
	runtime.GC()
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	return float64(m.HeapAlloc) / (1 << 20)
}

const n = 1_000_000

func main() {
	base := heapMB()

	in := &Interner{m: map[string]string{}}
	strs := make([]string, n)
	for i := range strs {
		strs[i] = in.Intern("user-session-" + strconv.Itoa(i))
	}
	fmt.Printf("map interner, in use:   %5.1f MB\n", heapMB()-base)
	strs = nil
	fmt.Printf("map interner, after GC: %5.1f MB\n", heapMB()-base)
	runtime.KeepAlive(in)
	in = nil

	base = heapMB()
	handles := make([]unique.Handle[string], n)
	for i := range handles {
		handles[i] = unique.Make("user-session-" + strconv.Itoa(i))
	}
	fmt.Printf("unique, in use:         %5.1f MB\n", heapMB()-base)
	handles = nil
	fmt.Printf("unique, after GC:       %5.1f MB\n", heapMB()-base)
	// unused entries are removed in the background
	time.Sleep(time.Second)
	fmt.Printf("unique, a bit later:    %5.1f MB\n", heapMB()-base)
}
map interner, in use:   102.8 MB
map interner, after GC: 102.8 MB
unique, in use:         177.0 MB
unique, after GC:       139.2 MB
unique, a bit later:      0.0 MB

The map interner keeps all 1 million strings after the program stopped using them. With unique, the values become garbage once the handles are gone. Removing entries from the internal table happens in the background after a GC cycle, so the memory isn't freed immediately, but it is freed.

Note also the "in use" numbers: with 1 million distinct values unique used more memory than the plain map. Each entry in its table has bookkeeping (a weak pointer, hash trie nodes). Interning saves memory only when values repeat.

Under the hood unique uses the same weak-pointer machinery that Go 1.24 exposed as package weak (see Weak pointers and cleanups). For how the garbage collector decides what is reachable, see Memory, escape analysis, and garbage collection.

A Symbol type

Using unique.Handle[string] directly everywhere is verbose and it prints badly. Wrapping it in a small named type gives you a String method and a clear name:

package main

import (
	"fmt"
	"strings"
	"unique"
)

// Symbol is an interned string: 8 bytes, compared in one instruction.
type Symbol struct {
	h unique.Handle[string]
}

func Sym(s string) Symbol { return Symbol{unique.Make(s)} }

func (s Symbol) String() string { return s.h.Value() }

type Metric struct {
	Name   Symbol
	Labels map[Symbol]Symbol
	Value  float64
}

var (
	symHost   = Sym("host")
	symMethod = Sym("method")
)

func parse(line string) Metric {
	// format: name value key=val key=val ...
	parts := strings.Fields(line)
	m := Metric{Name: Sym(parts[0]), Labels: map[Symbol]Symbol{}}
	fmt.Sscan(parts[1], &m.Value)
	for _, kv := range parts[2:] {
		k, v, _ := strings.Cut(kv, "=")
		m.Labels[Sym(k)] = Sym(v)
	}
	return m
}

func main() {
	lines := []string{
		"http_requests 12 host=web1 method=GET",
		"http_requests 3 host=web2 method=POST",
		"http_requests 7 host=web1 method=POST",
	}
	web1 := Sym("web1")
	var total float64
	for _, l := range lines {
		m := parse(l)
		fmt.Println(m.Name, m.Labels[symHost], m.Labels[symMethod], m.Value)
		if m.Labels[symHost] == web1 {
			total += m.Value
		}
	}
	fmt.Println("web1 total:", total)
}
http_requests web1 GET 12
http_requests web2 POST 3
http_requests web1 POST 7
web1 total: 19

A struct with a single comparable field is itself comparable, so Symbol works with == and as a map key, and it's still 8 bytes. Well-known symbols like symHost are made once in package-level variables, so the hot path doesn't call unique.Make for them. Because they are package-level variables, those values stay interned for the life of the program.

How net/netip uses it

unique was created for net/netip. A netip.Addr stores an IPv6 address as a 128-bit number plus details: whether it's IPv4 or IPv6 and the IPv6 zone (like eth0 in fe80::1%eth0). The details are stored as a handle:

// from net/netip/netip.go
type Addr struct {
	addr uint128
	z    unique.Handle[addrDetail]
}

type addrDetail struct {
	isV6   bool   // IPv4 is false, IPv6 is true.
	zoneV6 string // != "" only if IsV6 is true.
}

That keeps Addr small and makes it a comparable value type: you can use == on addresses and use them as map keys, zone included.

package main

import (
	"fmt"
	"net/netip"
	"unsafe"
)

func main() {
	a := netip.MustParseAddr("fe80::1%eth0")
	b := netip.MustParseAddr("fe80::1%eth0")
	c := netip.MustParseAddr("fe80::1%eth1")

	fmt.Println("a == b:", a == b)
	fmt.Println("a == c:", a == c)
	fmt.Println("zone:", a.Zone())
	fmt.Println("sizeof netip.Addr:", unsafe.Sizeof(a))

	// Addr is comparable, so it's a good map key
	seen := map[netip.Addr]int{}
	for _, s := range []string{"10.0.0.1", "fe80::1%eth0", "10.0.0.1", "fe80::1%eth0"} {
		seen[netip.MustParseAddr(s)]++
	}
	fmt.Println(seen)
}
a == b: true
a == c: false
zone: eth0
sizeof netip.Addr: 24
map[10.0.0.1:2 fe80::1%eth0:2]

Compare that with the older net.IP, which is a []byte and can't be compared with == or used as a map key. The zero Handle also has a use in netip: an Addr whose z is the zero handle is the invalid, zero Addr{}.

The pattern is worth copying: when a type has a rarely-varying, variable-size part (a string), intern it so the whole type stays a small, fixed-size, comparable value.

Pitfalls

package main

import (
	"fmt"
	"math"
	"unique"
)

type Config struct {
	Name string
	Tags *[]string
}

func main() {
	// 1. zero Handle
	var zero unique.Handle[string]
	fmt.Println("zero == Make(\"\"):", zero == unique.Make(""))
	func() {
		defer func() { fmt.Println("zero.Value() panics:", recover()) }()
		fmt.Printf("zero.Value(): %q\n", zero.Value())
	}()

	// 2. pointers are interned by address, not by what they point to
	x, y := 5, 5
	fmt.Println("Make(&x) == Make(&y):", unique.Make(&x) == unique.Make(&y))

	// 3. Value returns a shallow copy
	tags := []string{"a"}
	h := unique.Make(Config{Name: "cfg", Tags: &tags})
	tags[0] = "changed"
	fmt.Println("tags seen through handle:", *h.Value().Tags)

	// 4. NaN is not equal to itself
	n1, n2 := unique.Make(math.NaN()), unique.Make(math.NaN())
	fmt.Println("Make(NaN) == Make(NaN):", n1 == n2)

	// 5. interface types: comparable at compile time, may panic at run time
	func() {
		defer func() { fmt.Println("Make[any] of a slice:", recover()) }()
		unique.Make[any]([]int{1, 2})
	}()
}
zero == Make(""): false
zero.Value() panics: runtime error: invalid memory address or nil pointer dereference
Make(&x) == Make(&y): false
tags seen through handle: [changed]
Make(NaN) == Make(NaN): false
Make[any] of a slice: runtime error: hash of unhashable type []int
  1. The zero Handle is not a handle of the zero value. It's not equal to unique.Make("") and calling Value() on it panics. If a struct field may be unset, either check h == unique.Handle[T]{} or initialize it.
  2. Pointers are compared by address. Make(&x) interns the pointer, not the value it points to. Usually you want to intern the value itself.
  3. Value() returns a shallow copy. If T contains pointers, the interned value shares them with whoever created it. Treat interned values as immutable.
  4. Equality is Go's ==. NaN != NaN, so every Make(math.NaN()) creates a new entry, and +0.0 and -0.0 map to the same handle. Floating point keys are a bad idea here, just like in maps.
  5. Interface types can panic. unique.Make[any] compiles, but panics if the dynamic value isn't hashable, the same as using it as a map key.

When not to use unique

Good fits are data with low cardinality and high repetition, held in memory for a long time: parsed log fields, metric and tag names, header names, file paths in a build system, words in a text index, and identifiers in a compiler or interpreter.

Summary

See Strings for the basics of strings, and Equality and comparison for what == means for different types.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents