Performance 为什么';t型提示是否可以提高此功能的性能?
代码如下:Performance 为什么';t型提示是否可以提高此功能的性能?,performance,clojure,type-hinting,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")))) (tim
(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"))))
本例中的类型提示根本不能提高性能,为什么?类型提示仅在Clojure编译器无法推断类型的情况下才能提高运行时性能。在函数的
第一个字符中,(或a b)
表达式的或
是一个宏,它被扩展为如下所示
(let* [or__3975__auto__ a] (if or__3975__auto__ or__3975__auto__ b))
因为Clojure编译器知道a
和b
都有类型String
,所以它可以推断(或a b)
的结果类型,而不需要额外的类型提示(或a b)
总之,您不必在Clojure编译器可以推断类型的地方添加类型提示。您可以通过打开*反射时警告*
来检查Clojure编译器是否能够成功推断类型。不确定,但可能是因为子字符串
是一个java.lang.String
方法,因此,编译器已经可以知道它是一个字符串了?编译器不能保证在运行时可能存在哪些类和方法,所以它不能知道substring
是一个只存在于字符串中的方法。