What is the size in memory of the Clojure keyword?

I am writing a function in Clojure to estimate the memory size in the parsed JSON, for example:

(defn object-size
  [object]
  (cond
    (sequential? object)
      (reduce + (map object-size object))
    (map? object)
      (reduce
        (fn [total [k v]]
          (+ total (keyword-size k) (object-size v)))
        0
        object)
    :else
      (case (type object)
        java.lang.Long 8 
        java.lang.Double 8
        java.lang.String (* 2 (count object))
        ;; other data types
      )))

      

Obviously I need to add overhead for clojure.lang.PersistentVector

, java.lang.String

etc.

However, I'm not sure how to find the amount of memory clojure.lang.Keyword

, keyword-size

in the above example. How does Clojure store keywords? Are they constants similar to C ++ enum

, or are they a special case java.lang.String

that depends on the length?

+3


source to share


1 answer


The answer to this question from Clojure is basically impossible. Your first draft function works well for the most basic data structures, although even this simplest attempt has a few bugs already.

But more than that, this is just a poorly formulated question. What is the size xs

in this snippet?

(def xs (let [forever (promise)]
          (deliver forever
                   (lazy-seq (cons 1 @forever)))
          @forever))

user=> (take 5 xs)
(1 1 1 1 1)

      



xs

- an infinitely long sequence (so your snapshot will never complete, but if it could, it would definitely return "this is infinite"). But it actually takes up a small, fixed amount of memory because it is circular.

You can say ok, this is a dumb object, I don't mind if my function is not suitable for such objects. But in a common lazy garbage-collected language, cases with similar characteristics are common. If you exclude them, you exclude anything that is interesting.

+3


source







All Articles