Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know where to put type hints to improve numeric performance in Clojure?

In the Clojure documentation on type hinting, it has the following example on how type hinting and coercions can make code run much faster:

(defn foo [n]
  (loop [i 0]
    (if (< i n)
      (recur (inc i))
      i)))

(time (foo 100000))
"Elapsed time: 0.391 msecs"
100000

(defn foo2 [n]
  (let [n (int n)]
    (loop [i (int 0)]
      (if (< i n)
        (recur (inc i))
        i))))

(time (foo2 100000))
"Elapsed time: 0.084 msecs"
100000

If you run this code with (set! *warn-on-reflection* true), it doesn't show a reflection warning. Is it up to programmer trial-and-error to see where these kinds of adornments make a performance difference? Or is there a tool that indicates the problematic areas?

like image 577
Ana Avatar asked Oct 30 '22 17:10

Ana


1 Answers

Well you can estimate this pretty well, just by thinking about which parts of the code gets hit often.

Or you could use a normal profiler of some sort. I would recommend VIsual VM, which you can get to work with clojure. Then you just place them in the methods you see take most of the time (it will also show you calls to java.lang.reflect.Method, if this gets called a lot you should consider using type hints).

like image 103
Astrogat Avatar answered Nov 08 '22 06:11

Astrogat