I am writing a function that has to wrap other code. One simple
approach is to do
user> (defn wrap-fun [f]
(fn [& args]
(println "pre-processing")
(let [res (apply f args)]
(println "post-processing")
res)))
#'user/wrap-fun
user> (def w (wrap-fun (fn [x y] (println "calling") (+ x y))))
#'user/w
user> (w 2 2)
pre-processing
calling
post-processing
4
user>
I was wondering what is the cost of using apply vs calling the wrapped
function directly. So my first question is: what is the performance
cost of using apply vs calling a function ;-) Can the compiler inline
a call to apply so there is no difference, or is there a real cost?
An alternative is to use a macro to inline an expression corresponding
to the function f in wrap-fun above, e.g.,
user> (defmacro wrap-fn [params exp]
`(fn ~params
(println "pre-processing")
(let [res# ~exp]
(println "post-processing")
res#)))
#'user/wrap-fn
user> (def w (wrap-fn [x y] (do (println "calling") (+ x y))))
#'user/w
user> (w 2 2)
pre-processing
calling
post-processing
4
user>
This avoid calling apply. To answer my own question, I wanted to test
the performance difference between the inlined and the apply-based
approach. But given that micro-performance test are known to be hard^1
I wanted to make sure I was running the -server VM and that the code
was getting JIT'ed.
I tried starting a clojure REPL with the option -XX:-
PrintCompilation, but I never see any prints.
java -server -XX:-PrintCompilation -cp $CLOJURE_JRE_LIBS:
$USER_CLASSPATH clojure.main
I've done a dotimes where I call a wrapped function many times.
Now my question, is the code not JIT'ing or am I providing the wrong
JVM options?
/Karl
^1 http://www.azulsystems.com/events/javaone_2009/session/2009_J1_Benchmark.pdf
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en