# What is string interning?

> String interning keeps one copy of each distinct string so equality becomes a pointer comparison. How clox does it with its hash table.

**String interning**: String interning stores exactly one copy of each distinct string value, so two equal strings are always the same object and can be compared by address.

**String interning** means keeping a table of every distinct string and always reusing the stored copy. If "hello" is interned, every "hello" in the program is the same object, so checking two strings for equality is a single pointer comparison instead of a character-by-character loop.

## Why a VM wants it

Variable names, method names and field names are looked up constantly. With interning, a hash table keyed by strings can compare keys by pointer, which makes globals, fields and method calls fast. The price is a lookup in the intern table every time a new string is created.

## In clox

[Chapter 20, Hash Tables](https://cracked.guide/guide/ci-20) builds an [open addressing](https://cracked.guide/glossary/open-addressing) hash table and uses it as the intern table. Later, the [garbage collector](https://cracked.guide/glossary/mark-sweep-garbage-collection) has to treat that table as weak: an interned string nobody else uses must still be freed.

## Questions

### Do real languages intern strings?

Many do for identifiers and literals, and some intern all strings. Java interns string literals, for example, and exposes intern() for others.

---

Source: https://cracked.guide/glossary/string-interning
cracked.guide: A free, dated 145-week path to getting genuinely cracked at programming.
