viebel
viebel

Reputation: 20670

assoc in clojure: explanation of the internals

Here is the code for assoc:

(def assoc
 (fn assoc
   ([map key val] (. clojure.lang.RT (assoc map key val)))))
  1. What is the meaning of clojure.lang.RT?

  2. What is the complexity of calling assoc on a vector/map?

  3. What is the complexity of accessing a structure that has been created by assoc?

Upvotes: 3

Views: 440

Answers (1)

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91554

  1. clojure.lang.RT is the main Clojure RunTime class. It has most of the methods that make up the core of the language.

  2. assoc is O(1) for all the associative data structure including vectors and maps. array-map starts out linear for the first few item, then promoted itself to a hash-map so it is O(1) as well. You could of course implement the associative interface with something that is not O(1) if you need to.

  3. Technically the access time for an item in a map or vector that was created by calling assoc on another map is O(log32 N). Because these data structures have an upper bound on the size of ~2^32 items this leaves a maximum tree depth of six which effectively constant time

Clojure's associative data structures are all O(nLog n) in space (because they are trees).

Upvotes: 4

Related Questions