gpt4 book ai didi

performance - clojure - :refer vs :as

转载 作者:行者123 更新时间:2023-12-03 13:54:03 25 4
gpt4 key购买 nike

我正在学习 clojure。
作为 :require 的一部分过程,有一个选项可以使用 :refer对于特定方法或所有方法。

或使用 :as然后选择您需要的方法。

我想我了解这两个选项之间的区别,并且还看到了文档 here说的是:

:as takes a symbol as its argument and makes that symbol an alias to the lib's namespace in the current namespace.

:refer takes a list of symbols to refer from the namespace or the :all keyword to bring in all public vars.



但我仍然不确定:
  • 我什么时候应该使用一个选项而不是另一个?
  • 有没有性能差异在这两个选项之间? (我的想法是没有,因为编译器会优化这两个选项

  • (我还做了两个使用 core.asyc 的小程序,一个使用 :as ,一个使用 :refer 。运行两者所用的时间几乎相同。

    最佳答案

    我几乎总是使用 :as像这样:

    (ns demo.core
    (:require
    [clojure.string :as str] ))

    (println (str/join ["hello" "there"]))

    这让读者看到 join属于 str (命名空间别名),他们可以很容易地看到 join解析为 clojure.string/join .

    考虑替代方案:
    (ns demo.core
    (:require
    [clojure.string :refer [join] ))

    <snip>
    ...397 lines of other code...
    </snip>

    (println (join ["hello" "there"]))

    这里 join看起来像 demo.core 中定义的局部函数,读者可能需要一段时间才能弄清楚它的来源。他们仍然可以通过查看 ns 来追溯起源。声明,但除非它是一个非常常见的函数,否则大多数人都同意命名空间别名技术在阅读您没有编写的代码时更容易/更快地理解。

    在执行时,编译器会将两种形式转换为相同的机器码,因此没有区别。

    关于performance - clojure - :refer vs :as,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57913343/

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