tags:

views:

205

answers:

2

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?

+4  A: 

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.

tomjen
Thanks for correcting my incorrect understanding on how type hints work. I still feel the larger question about caching reflection is unanswered, but will accept that the implication is that it is not straightforward if at all possible.
Timothy Pratley
+1  A: 

Rich was kind enough to enlighten me: "The real answer for the JDK proper is JSR 292, which allows for the proper construction of call site caches with performance much better than memoizaton."

Timothy Pratley