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

时间:2015-05-06 15:34:51

标签: 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"))))

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

1 个答案:

答案 0 :(得分:7)

类型提示仅在Clojure编译器无法推断类型的情况下提高运行时性能。在first-char-of-either函数中,or表达式的(or a b)是一个宏,它会扩展为这样。

(let* [or__3975__auto__ a] (if or__3975__auto__ or__3975__auto__ b))

因为Clojure编译器知道ab都有类型String,所以它可以推断出(or a b)的结果类型而没有额外的类型提示{{1} }。

总而言之,您不必在Clojure编译器可以推断类型的位置添加类型提示。您可以通过打开(or a b)来检查Clojure编译器是否可以成功推断类型。