by MillenialMan · 5y ago · 0 comments
The data structure that drives the immutable variables, the Hash-Array Mapped Trie, is efficient in terms of time- and space- complexity, but it's incredibly CPU cache-unfriendly because by nature it's fragmented - it's not contiguous in RAM. Any operation on a HAMT will be steeped in cache misses, which slows you down by a factor of hundreds to thousands. The longer the trie has been around, the more fragmented it is likely to become. Looping over a HAMT is slower than looping over an array by two or three orders of magnitude.
I don't think there is really a solution to that. It's inherent. Clojure will always be slow, because it's not cache friendly. The architecture of your computer means you physically can't speed it up without sacrificing immutability.
How does Clojure's HAMT avoid fragmenting over time?
> Clojure standard library works on arrays just fine, as demonstrated in the article.
Right, but then you don't have immutability - so you lose all the guarantees that you originally had with immutable-by-default.
Hello, author here :)
HAMTs are certainly slower, for "churning" operations, i.e., lots of updates, which is where Clojure exposes the transient API, which gives you limited localized mutability (some terms and conditions may apply)
Where iteration is concerned, they standard library implementation is pretty good. It relies on chunks of 64 element arrays which store the keys and values contiguously. Thus, APIs which expose direct iteration, Iterator and IReduce(Init) operate on these chunks one at a time. It isn't as fast as primitive arrays, but it's pretty fast.
Not really, for example take the following solution with execution time mean : 1.678226 ms
(defn smt-8''' [^ints times-arr]
(loop [res (transient []) pointer-1 (int 0) pointer-2 (int 7)]
(if (< pointer-2 (alength times-arr))
(let [start-element (aget times-arr pointer-1)
end-element (aget times-arr pointer-2)
time-diff (- end-element start-element)]
(recur
(if (< time-diff 1000)
(conj! res [(mapv #(aget times-arr (+ pointer-1 (int %))) (range 8))
time-diff])
res)
(inc pointer-1)
(inc pointer-2)))
(persistent! res))))
It only requires the input being an array, but it will return an immutable persistent vector of vectors. So it is very easy to selectively go down to an array in the performance critical sections while being immutable and idiomatic in most places.> he doesn't really explain why HAMTs specifically are slow
Take this solution using HAMT vectors with execution time mean : 23.567174 ms
(defn smt-8' [times-vec]
(loop [res (transient []) pointer-1 (int 0) pointer-2 (int 7)]
(if-let [end-element (get times-vec pointer-2)]
(let [end-element (int end-element)
start-element (int (get times-vec pointer-1))
time-diff (- end-element start-element)]
(recur
(if (< time-diff 1000)
(conj! res [(subvec times-vec pointer-1 (inc pointer-2))
time-diff])
res)
(inc pointer-1)
(inc pointer-2)))
(persistent! res))))
Now it is 14 times slower than my prior one which iterates over an array, but it is still pretty fast, so that's OP's point, things are often sufficiently fast, and when they are not you can selectively optimize those parts, and easily too, see how similar my two solutions are from one another.Edit: These assume you've `(set! unchecked-math true)` prior to compiling the functions.
Are there any other key/value data structures where insertion and retrieval are less than O(n) in complexity, but where the memory layout is better ordered for cache hits during searches? Maybe good old red-black trees?
Worth checking out are BTrees and Hitchhiker trees, but I think a definitive answer will be implementation dependent even in those cases, i.e. one might win out over the other for a specific branch factor or other tune-able parameters
However, not every use case can benefit from cache optimization and you can use other data structures. It’s not super useful to make generalizations about performance that way.
Aeron comes to mind as an example in regards to high performance solutions that uses them. But a more fundamental reason is that immutability can be part of your domain logic. Think video games like braid, or business applications where you need to derive a lot of different views and go back and forth between them, or domains where data just is inherently immutable such as accounting and so on.
> Think video games like braid
Braid doesn't use immutable data structures, it uses a historical record (and immutability would be incompatible with some of the mechanics).[1] The author of Braid is actually quite famous for his dislike of functional languages and immutability. He doesn't even like garbage collection because of the overhead it introduces.
Interestingly, he was talking about data structures for codebase representation (in the context of a compiler) a while back, and someone mentioned HAMTs. I'm definitely curious if they would work well there.
Hope some performance experts can chime in but this might be related to data structure sharing between caches or allocation contention in the JVM.
https://clojureverse.org/t/parallel-transducing-context-figh...
https://www.reddit.com/r/Clojure/comments/emylbs/any_idea_wh...
https://clojurians.zulipchat.com/#narrow/stream/151168-cloju...
https://github.com/joinr/paralleltest/issues/1
Anything in particular you're looking for?
For a HAMT, With depth (eg) 2, you should be able to prefetch the next node in your iteration while you iterate the current node of 64 elements. Actually iterating through the objects is going to suck but hopefully you can prefetch enough of them too. (Or maybe hotspot could online things enough to improve memory access patterns a bit to take advantage of ILP). There’s still the problem that you can’t read main memory sequentially except that often all the objects in a HAMT were allocated sequentially so you can read main memory sequentially (as allocation is typically just bumping a pointer, allocation-time-locality tends to correspond to address-locality)
> Clojure will always be slow, because it's not cache friendly.
You always have the option to use the java data structures, for the cases this kind of optimization is needed.
Replacing the critical path is an option, but that only works for numpy-style situations where you can cleanly isolate the computational work and detach it from the plumbing. If your app is slow because the inefficiencies have added up across the entire codebase (more common, I would argue), that's not an easy option.
Python is also slow, but you can still go fast (in some cases) by calling into C libraries like numpy - but the performance is coming from C, not Python. Python is still slow, it's just not an issue because you're only using it for plumbing.
But Clojure is immutable-by-default, that's the point of the language - it gives you various guarantees so you don't have to worry about mutability bubbling up from lower levels. In order to wrap your heavy path you have to go outside the Clojure structure and sacrifice that guarantee. You do lose structural integrity when you do that, even if you attempt to insulate your mutable structure. The system loses some provability.
This is where I would have to disagree, in my experience, that is less common. Generally there are specific places that are hot spots, and you can just optimize those.
Could be it depends what application you are writing, I tend to write backend services and web apps, for those I've not really seen the "inefficiencies have added up", generally if you profile you'll find a few places that are your offenders.
"Slow" is also very relative.
(cr/quick-bench (reduce (constantly nil) times-vector))
Execution time mean : 3.985765 ms
(cr/quick-bench (dotimes [i (.size times-arraylist)]
(.get times-arraylist i)))
Execution time mean : 775.562574 µs
(cr/quick-bench (dotimes [i (alength times-array)]
(aget times-array i)))
Execution time mean : 590.941280 µs
Yes iterating over a persistent vector of Integers is slower compared to ArrayList and Array, about 5 to 8 times slower. But for a vector of size 1000000 it only takes 4ms to do so.In Python:
> python3 -m timeit "for i in range(1000000): None"
20 loops, best of 5: 12.1 msec per loop
It take 12ms for example.So I would say for most uses, persistent vectors serve as a great default mix of speed and correctness.