liveBook · Manning

Interning

As explained in Clojure: The Essential Reference

Interning is a caching technique that reuses a single object instance for equivalent values, such as selected literals.

Interning caches equivalent values so later constructions can reuse one object instance. It can reduce memory use, especially for keywords used as map keys, while adding lookup overhead. section 15.1

Interning matters when object identity is observable:

  • Keywords are interned: `(identical? (keyword "a") (keyword "a"))` returns `true`, whereas separately created symbols do not share identity. section 15.1
  • `identical?` checks whether two references point to the same instance, not whether their values are merely equal; use it for identity-sensitive cases such as sentinel objects. section 6.5
  • Interning is implementation-dependent across basic values: empty lists and some numeric literals may share identity, while separately constructed values often do not. section 6.5

Keyword interning versus symbol construction

(identical? (symbol "a") (symbol "a")) ;; false (identical? (keyword "a") (keyword "a")) ;; true (find-keyword "never-created") ;; nil (find-keyword "doc") ;; :doc section 15.1

(identical? (symbol "a") (symbol "a")) ; #1
;; false

(identical? (keyword "a") (keyword "a")) ; #2
;; true

Compare identity results for separately constructed symbols and keywords. section 15.1

(require '[criterium.core :refer [quick-bench]])

(quick-bench (symbol "a"))  ; #1
;; Execution time mean : 3.663330 ns
(quick-bench (keyword "a")) ; #2
;; Execution time mean : 11.791798 ns

Observe the measured construction-time cost of symbol creation versus keyword creation. section 15.1

How Clojure: The Essential Reference covers it

How deep it goes
Explains caching, identity consequences, memory benefits, speed costs, and lookup behavior without detailing cache internals.
Examples
Demonstrates keyword and symbol construction, identical? comparisons, find-keyword queries, and construction-time benchmarks.
What you can do after
Evaluate object identity correctly and recognize when interning affects memory, speed, and identical? results.
How it connects
Connects object identity, equality, keywords, symbols, maps, memory usage, and performance benchmarking.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.