wirrbel
wirrbel

Reputation: 3299

ClojureScript Hash Map performance vs. Javascript Objects

I am working with big JSON files (that basically contain tree-like structures) in a ClojureScript app. Basically I iterate over all elements in that tree structure and these are quite a bunch of operations. Now I wonder how much overhead the Lazy Hash map treatment causes.

Basically I:

The JSON's structure consists of nested lists and hash-maps. Something like

{:A-key-a [{:B-key-a 34  :B-key-b [213. 23.4]}
                   {:B-key-a 34  :B-key-b [213. 23.4]}
                   ...] 
 :A-key-b [{:someother-a 30 ...}
                   ...]
 ...}

Now I wonder if I should fall back to direct JS object usage to gain spped. Intuitively I would think that this is faster than the ClojureScript objects on the other hand I do not want to optimize prematurely and I do not know enough about the internals of ClojureScript in order to judge the overheads introduced by lazy evaluation.

I kind of figure that I could use .-mykey accessor syntax and google closure foreach functions in order to rewrite that specific source code. What do you think?

I have seen Improve performance of a ClojureScript program on a similar optimation topic and I think this also implies that loop .. recur seems to be a viable option for looping. Is that right?

Upvotes: 2

Views: 1784

Answers (1)

deprecated
deprecated

Reputation: 5242

If it is under your control, consider producing EDN instead of JSON on the server side. I'm not sure if parsing a EDN string is faster than converting JSON to EDN, but at the very least it will reduce your app's complexity to some degree.

As per your description, it sounds like the data structure will be "read-only". Then the object construction cost is practically the only one you have to consider - reading it later will be cheap (persistent maps and vectors have near-constant access time).

Depending on the data structure size, the user might or not might not perceive how the UI blocks due to this computational task at page-load time. Consider measuring it.

Between that JS arrays can be treated as seqs, and that keyword keys are not as powerful in ClojureScript as they are in Clojure (here they do not implement IFn), there actually aren't that many advantages of EDN over JSON in this particular case.

As for iteration, while maps/vectors aren't lazy, the results of Clojure(Script)'s data processing functions (map/filter/etc) do return lazy sequences - and generate intermediate collections in the way.

You can avoid the associated overhead by using the recently-ported reducers library, and the transient/persistent! facilities (if this turned out to be an actual issue in your app).

Upvotes: 2

Related Questions