How many variables got created in total inside a loop using `let`

Viewed 92

I wrote the following function to print a value for 10 times:

(defn test-let []
  (loop [index 0]
    (when (< index 10)
      (let [x 2]
        (println "Value of x: " x))
      (recur (inc index)))))

My question is:

  1. Did because of let inside the loop, 10 variables (representing the value 2) and only 1 symbol (x, that represent the variable that holds value 2) got created?

  2. If 10 variables were created, at what point they qualify for garbage collection?

1 Answers

I think you are mixing up values and variables. In your example above, there are 10 values created each time in the loop and are bound to x each time. In Clojure, the local symbols (aka names) created by a let form are not variables (for example, like those top level symbols created by def). Inside a let the symbols are just directly bound to the values. See https://clojure.org/reference/special_forms#let for more. The Clojure compiler does locals clearing, and will generate code to remove references to local values once the locus of control leaves the local scope. See https://clojure.org/reference/compilation#_locals_clearing for more details. In your particular case of a value of 2 it probably does not mater since Clojure will use the primitive value directly. I presume you were asking for the more general case where the value that is bound to x may be bigger than just a primitive.

Related