This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2018-10-14
Channels
- # announcements (1)
- # beginners (13)
- # calva (2)
- # cider (43)
- # cljdoc (11)
- # clojure (16)
- # clojure-spec (10)
- # clojure-uk (6)
- # clojurescript (7)
- # code-reviews (3)
- # core-matrix (1)
- # datascript (4)
- # datomic (7)
- # devcards (4)
- # figwheel-main (12)
- # fulcro (27)
- # hoplon (1)
- # lein-figwheel (1)
- # luminus (1)
- # nrepl (23)
- # off-topic (4)
- # planck (1)
- # re-frame (8)
- # reagent (7)
- # shadow-cljs (61)
- # spacemacs (7)
- # tools-deps (19)
Anyone here knows how I could invoke a static method on a class from one of its instance?
I have a (defrecord Foo [bar baz])
and I want to access Foo/create
but the only reference I have is an instance of Foo
. I tried (.create (class foo-instance) {})
but this searches amongst instance methods. Any ideas?
user=> (defrecord Foo [bar])
user.Foo
user=> (let [inst (Foo. 1)] (clojure.lang.Reflector/invokeStaticMethod (.getName (class inst)) "create" (object-array [{:bar (.-bar inst)}])))
#user.Foo{:bar 1}
Didn't knew about c.l.Reflector/invokeStaticMethod
! I'm going to try that. Thank you!
It did the trick :thumbsup:
While it is easy to come up with an example where type-hinting a function argument with ^long
has a performance advantage, I cannot find an example where hinting the return of the function makes any difference. Can anyone suggest one?
I thought maybe (defn foo ^long [] 5)
would make a difference in
(time (dotimes [x 10000000] (+ (foo) (foo))))
But apparently not
if you used criterium
instead of time
+`dotimes` you would've noticed that it is indeed faster than using (defn bar [] 5)
well, that benchmarking using time
works well enough in the hinted parameter example (and is on the http://clojure.org site for its examples of type hinting performance gains)
[~]> clj -A:bench
Clojure 1.10.0-master-SNAPSHOT
user=> (use 'criterium.core)
nil
user=> (defn bar [] 5)
#'user/bar
user=> (defn foo ^long [] 5)
#'user/foo
user=> (quick-bench (+ (foo) (foo)))
Evaluation count : 135075996 in 6 samples of 22512666 calls.
Execution time mean : 2.208218 ns
Execution time std-deviation : 0.422297 ns
Execution time lower quantile : 1.935788 ns ( 2.5%)
Execution time upper quantile : 2.928008 ns (97.5%)
Overhead used : 2.390831 ns
Found 1 outliers in 6 samples (16.6667 %)
low-severe 1 (16.6667 %)
Variance from outliers : 48.2198 % Variance is moderately inflated by outliers
nil
user=> (quick-bench (+ (bar) (bar)))
Evaluation count : 35692152 in 6 samples of 5948692 calls.
Execution time mean : 15.873007 ns
Execution time std-deviation : 1.651083 ns
Execution time lower quantile : 14.405037 ns ( 2.5%)
Execution time upper quantile : 17.695135 ns (97.5%)
Overhead used : 2.390831 ns
nil