liveBook · Manning

Unchecked-math

As explained in Clojure: The Essential Reference

unchecked-math is a Clojure dynamic variable that enables compiler optimizations using unchecked arithmetic and primitive JVM operations.

*unchecked-math* is a dynamic variable that lets Clojure compile eligible bit-wise, arithmetic, and array operations directly to JVM instructions instead of routing them through clojure.lang.Numbers. It also removes boundary checks, so arithmetic can overflow rather than promote or report it. section 23.19

The optimization depends on primitive Java types. Type hints such as ^long prevent argument auto-boxing and let the compiler select primitive operations; without them, expressions may remain boxed and lose the intended optimization. section 5.13 section 23.19

Enabling unchecked arithmetic

(set! *unchecked-math* true) (defn sum ^long [^long a ^long b] (+ a b)) (sum 1 2) ;; 3 (set! *unchecked-math* :warn-on-boxed) (defn partial-sum [^long a b] (+ a b)) ;; Boxed math warning section 23.19

Overflow is intentional

(unchecked-inc (long (Math/pow 2 63))) ;; -9223372036854775808 (unchecked-dec (long (- (Math/pow 2 63)))) ;; 9223372036854775807 section 5.13

(set! *unchecked-math* true) ; #1

(defn sum ^long [^long a ^long b] ; #2
  (+ a b))

(sum 1 2)
;; 3

Compare ordinary arithmetic with compiler-directed unchecked arithmetic while retaining primitive type hints. section 23.19

Use *unchecked-math* when overflow checks and numeric promotion are unnecessary and primitive performance matters. Pair it with type hints, and use :warn-on-boxed to expose calls that still involve boxed values. section 5.13 section 23.19

How Clojure: The Essential Reference covers it

How deep it goes
Explains JVM dispatch, removed boundary checks, primitive requirements, boxing caveats, and overflow examples, but not broader compiler internals.
Examples
Uses optimized sum functions, boxed-math warnings, unchecked operators, and long-boundary overflow examples.
What it assumes
Assumes familiarity with Clojure arithmetic and type hints while demonstrating primitive dispatch and unchecked overflow behavior.
What you can do after
Apply it via *unchecked-math*, primitive type hints, and :warn-on-boxed to optimize arithmetic and inspect boxing.
How it connects
Connects unchecked arithmetic with type hints, primitive types, auto-boxing, JVM instructions, and reflection warnings.

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.