String Interner (Go)
Topics: profiling, memory optimization, allocations
Problem
Parsers, log processors, and symbol tables see the same strings over and over. Interning keeps a
single canonical copy of each distinct value so the duplicates' backing arrays can be freed — a
classic way to cut memory and allocations. Build one.
type Interner struct { /* ... */ }
func New() *Interner
func (in *Interner) Intern(s string) string
func (in *Interner) Len() int
Intern(s) returns a string equal to s. Equal inputs return equal results.
- Duplicates share one backing array: interning a value already seen returns the stored copy,
so two equal interned strings have the same underlying data pointer.
- No allocation on a hit: re-interning a known value must not allocate (the test checks with
testing.AllocsPerRun). Cloning on every call fails this.
Len returns the number of distinct strings interned.
The whole thing is a map[string]string: on a miss, store s as its own canonical copy; on a hit,
return the stored value directly. A map lookup and returning an existing string header allocate
nothing — so the hot path (lots of duplicates) is allocation-free.
Sign in to submit your solution.