Programming

(Clojure) Type Hints

steloflute 2012. 12. 25. 23:36

http://clojure.org/java_interop#Java%20Interop-Type%20Hints


Type Hints


Clojure supports the use of type hints to assist the compiler in avoiding reflection in performance-critical areas of code. Normally, one should avoid the use of type hints until there is a known performance bottleneck. Type hints are metadata tags placed on symbols or expressions that are consumed by the compiler. They can be placed on function parameters, let-bound names, var names (when defined), and expressions:
(defn len [x]
  (.length x))
 
(defn len2 [^String x]
  (.length x))
 
user=> (time (reduce + (map len (repeat 1000000 "asdf"))))
"Elapsed time: 3007.198 msecs"
4000000
user=> (time (reduce + (map len2 (repeat 1000000 "asdf"))))
"Elapsed time: 308.045 msecs"
4000000
Once a type hint has been placed on an identifier or expression, the compiler will try to resolve any calls to methods thereupon at compile time. In addition, the compiler will track the use of any return values and infer types for their use and so on, so very few hints are needed to get a fully compile-time resolved series of calls. Note that type hints are not needed for static members (or their return values!) as the compiler always has the type for statics.

There is a *warn-on-reflection* flag (defaults to false) which will cause the compiler to warn you when it can't resolve to a direct call:
(set! *warn-on-reflection* true)
-> true
 
(defn foo [s] (.charAt s 1))
-> Reflection warning, line: 2 - call to charAt can't be resolved.
-> #user/foo
 
(defn foo [^String s] (.charAt s 1))
-> #user/foo
For function return values, the type hint can be placed before the arguments vector:

(defn hinted
  (^String [])
  (^Integer [a])
  (^java.util.List [a & args]))
 
-> #user/hinted





(set! *warn-on-reflection* true)
는 참 편리한 기능이다. 이게 default이면 좋겠다. (VB의 Option Explicit와 비슷한 느낌?)

(def ^TextArea text-out (new TextArea))

와 같은 경우, type hint를 안 주면 이게 new로 생성된 객체이지만 compiler는 type을 모른다. (Clojure 1.4에서는 Reflection warning 발생)