Clojure performance of lazy structures against hashes / sets / vectors?

I use Clojure data structures all over the place, but I do not use lazy evaluation. Is there a performance limit when using lazy structures around the world?

+6
source share
2 answers

From the source code:

clojure.lang.Cons (strict list item, clojure.lang.PersistentList very similar), https://github.com/clojure/clojure/blob/1.2.0/src/jvm/clojure/lang/Cons.java#L34

 public Object first(){ return _first; } 

clojure.lang.LazySeq (lazy element of the sequence), https://github.com/clojure/clojure/blob/1.2.0/src/jvm/clojure/lang/LazySeq.java#L77

 public Object first(){ seq(); if(s == null) return null; return s.first(); } 

Where

 final synchronized Object sval(){ if(fn != null) { try { sv = fn.invoke(); fn = null; } catch(Exception e) { throw new RuntimeException(e); } } if(sv != null) return sv; return s; } final synchronized public ISeq seq(){ sval(); if(sv != null) { Object ls = sv; sv = null; while(ls instanceof LazySeq) { ls = ((LazySeq)ls).sval(); } s = RT.seq(ls); } return s; } 

So, you definitely pay the price. It depends on each particular use case, how much this price affects you and whether it depends on memory savings and the lack of wasted calculations that a lazy estimate buys you.

+4
source

There is overhead for lazy structures (pmjordan's answer is great for giving you the details .....). My very rude assessment is that you pay a fine of 2-5 times.

However, there are some problems:

  • Lazy evaluation means that your working dataset may be smaller, as it is created only when necessary. This can improve cache utilization and therefore performance in some cases.
  • Lazy assessment will help you write simpler and more understandable code. Therefore, you can focus on writing the best algorithms. The advantage of using a better algorithm (for example, O (n log n) versus O (n ^ 2)) can cost a lot more than the overhead of a lazy estimate.

My advice would be to freely use a lazy rating if you are not sure that you are in a situation where you really need high performance and cannot afford the overhead (for example, image processing or something like that .. ..)

+3
source

Source: https://habr.com/ru/post/885796/


All Articles