gpt4 book ai didi

performance - 为什么类型提示不能提高这个函数的性能?

转载 作者:行者123 更新时间:2023-12-02 15:26:37 24 4
gpt4 key购买 nike

代码如下:

(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 编译器无法推断类型时提高运行时性能。在first-char-of-either 函数中,(or a b) 表达式的or 是一个宏,扩展成这样.

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

因为 Clojure 编译器知道 ab 的类型都是 String,所以它可以推断出 的结果类型(或a b) 没有额外类型提示到 (或 a b)

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

关于performance - 为什么类型提示不能提高这个函数的性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30081343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com