为什么不在此函数中键入提示提高性能?

qed*_*qed 2 performance clojure type-hinting

这是代码:

(defn first-char-of-either [^String a  ^String b]
  (.substring (or a b) 0 1))
(defn first-char-of-either1 [^String a  ^String b]
  (.substring ^String (or a b) 0 1))
(time (dorun (repeatedly 1000000 #(first-char-of-either  nil "abcde"))))
(time (dorun (repeatedly 1000000 #(first-char-of-either1 nil "abcde"))))
Run Code Online (Sandbox Code Playgroud)

在这种情况下类型提示根本不会提高性能,为什么?

tno*_*oda 7

只有在Clojure编译器无法推断类型的情况下,类型提示才能提高运行时性能.在first-char-of-either功能,or所述的(or a b)表达是一个宏,它被扩展成这样.

(let* [or__3975__auto__ a] (if or__3975__auto__ or__3975__auto__ b))
Run Code Online (Sandbox Code Playgroud)

因为Clojure的编译器知道这两个ab有型String,它可以推断的结果类型(or a b),无需额外类型提示到(or a b).

总而言之,您不必在Clojure编译器可以推断类型的位置添加类型提示.您可以通过打开来检查Clojure编译器是否可以成功推断类型*warn-on-reflection*.