liveBook · Manning

Constant time

As explained in Clojure: The Essential Reference

Constant time is an asymptotic complexity in which execution time does not grow with input size.

Constant time, written O(1), describes an operation whose execution time does not grow with input size. It is useful for distinguishing fixed-cost setup from work performed later or repeatedly. section 2.2.1 section 9.2.1

Clojure examples show three different meanings of an O(1) claim:

  • fnil generates a defaulting function in constant time, and invoking that generated function is also constant time when limited to its supported arities. section 2.2.1
  • Bitwise operations are practically constant time; dependencies on the number of bits are generally hardware-dependent and insignificant for ordinary use. section 3.2.3
  • repeatedly creates a lazy sequence in constant time, but fully consuming it takes O(n), and retaining its head can require O(n) memory. section 9.2.1

Constant setup does not mean constant total work

(let [rands (repeatedly 10000000 rand)] (first rands) (last rands)) ;; first access is immediate; later consumption performs the requested work (repeatedly generates the lazy sequence in O(1), while requesting items grows work and cached memory with n.) section 9.2.1

How Clojure: The Essential Reference covers it

How deep it goes
Distinguishes setup from consumption, invocation arity, hardware dependence, caching, and retained-head memory costs.
Examples
Uses fnil, bitwise operations, powerset generation, repeatedly, random values, and a large lazy sequence.
What you can do after
Evaluate complexity claims by separating eager setup, deferred consumption, supported arity, and retained data.
How it connects
Connects constant time with lazy sequences, bitwise operators, function generation, reduction, and memory retention.

Also explained in

Compare how 7 books explain constant time →

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.