Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java reflection in Clojure be memoized?

Tags:

clojure

Type-hints can make a huge improvement on execution time where reflection occurs many times. My understanding of type-hints is that it just allows the compiler to cache a reflection lookup. Can that caching occur dynamically? Or is there some reason this would be bad/impossible?

like image 879
Timothy Pratley Avatar asked Jan 24 '23 04:01

Timothy Pratley


1 Answers

From Programming Clojure:

These warnings indicate that Clojure has no way to know the type of c. You can provide a type hint to fix this, using the metadata syntax ^Class:

(defn describe-class [#^Class c]
{:name (.getName c)
:final (java.lang.reflect.Modifier/isFinal (.getModifiers c))})

With the type hint in place, the reflection warnings will disappear. The compiled Clojure code will be exactly the same as compiled Java code. Further, attempts to call describe-class with something other than a Class will fail with a ClassCastException.

So to sum up, the reflection cast isn't just cached it is eliminated.

like image 130
tomjen Avatar answered Jan 31 '23 05:01

tomjen