How does Clojure ^:const work?

前端 未结 3 2029
南笙
南笙 2020-12-10 10:16

I\'m trying to understand what ^:const does in clojure. This is what the dev docs say. http://dev.clojure.org/display/doc/1.3

(def consta

3条回答
  •  轮回少年
    2020-12-10 10:39

    In the example docs they are trying to show that in most cases if you def a var to be the result of looking something up in a map without using const, then the lookup will happen when the class loads. so you pay the cost once each time you run the program (not at every lookup, just when the class loads). And pay the cost of looking up the value in the var each time it is read.

    If you instead make it const then the compiler will preform the lookup at compile time and then emit a simple java final variable and you will pay the lookup cost only once total at the time you compile the program.

    This is a contrived example because one map lookup at class load time and some var lookups at runtime are basically nothing, though it illustrates the point that some work happens at compile time, some at load time, and the rest well ... the rest of the time

提交回复
热议问题