5

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?

1
  • 1
    There are no type hints in this code, int is a function, and here is given a long and returns an int. Commented Oct 8, 2015 at 13:34

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

I think this is a good but partial answer to Ana's question. Knowing which functions take the most time still doesn't tell you whether a coercion or hint will help. For that question, perhaps trial and error, or deep knowledge of the Clojure compiler is what's needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.