Why is there such a difference in speed between Clojure loops and iteration

My question is why there is such a difference in speed between the loop method and the iteration method in clojure. I completed the tutorial at http://www.learningclojure.com/2010/02/clojure-dojo-2-what-about-numbers-that.html and defined two square root methods using the Heron method:

(defn avg [& nums] (/ (apply + nums) (count nums)))
(defn abs [x] (if (< x 0) (- x) x))
(defn close [a b] (-> a (- b) abs (< 1e-10) ) )

(defn sqrt [num]
  (loop [guess 1]
    (if (close num (* guess guess))
        guess
     (recur (avg guess (/ num guess)))
)))

(time (dotimes [n 10000] (sqrt 10))) ;;"Elapsed time: 1169.502 msecs"


;; Calculation using the iterate method
(defn sqrt2 [number]
    (first (filter #(close number (* % %)) 
        (iterate #(avg % (/ number %)) 1.0))))

(time (dotimes [n 10000] (sqrt2 10))) ;;"Elapsed time: 184.119 msecs"

There is about x10 speed increase between the two methods, and I wonder what happens beneath the surface to make them so ring?

+5
source share
1 answer

Your results are surprising: usually loop / recur is the fastest Clojure looping construct.

, JVM JIT , loop/recur. , , Clojure: , , .

, , :

(set! *unchecked-math* true)

(defn sqrt [num]
  (loop [guess (double 1)]
    (if (close num (* guess guess))
      guess
      (recur (double (avg guess (/ num guess)))))))

(time (dotimes [n 10000] (sqrt 10)))
=> "Elapsed time: 25.347291 msecs"


(defn sqrt2 [number]
  (let [number (double number)]
    (first (filter #(close number (* % %)) 
      (iterate #(avg % (/ number %)) 1.0)))))

(time (dotimes [n 10000] (sqrt 10)))
=> "Elapsed time: 32.939526 msecs"

, loop/recur . Clojure 1.3

+5

All Articles