r/Clojure • • Aug 11 '18

Incremental Dom examples from Jane Street (OCaml)

ClojureScript will soon need this, in my opinion, because it fixes React.js's "100k problem". (100k problem is 100k items in state – maybe it reduces to one dom element with the sum, but the sum computation needs to be incremental, and the dom patch incremental, or performance fails with large state values.) If you want to have a big impact in the ClojureScript ecosystem (and bring Cljs to more people), beating React.js is a really great place to focus, I think.

PureScript's Halogen pivoted away from this problem and never released a satisfactory soln to the 100k problem, i believe.

Jane Street appears to have solved it in 2016 with OCaml: https://blog.janestreet.com/incrementality-and-the-web/

https://github.com/janestreet/incr_dom/blob/eee9268b7c9dfa802a744a235b9be9e03dc825c5/example/entry_table/entries.ml#L197

The readme says the view function is incremental and note the interesting comment on 184.

Incr.Map.filter_mapi' : https://blog.janestreet.com/self-adjusting-dom-and-diffable-data/

13 Upvotes

22 comments sorted by

3

u/isak_s Aug 14 '18

You may be interested in this ongoing web framework project:

https://github.com/kennytilton/mxtodomvc https://github.com/kennytilton/mxweb/tree/master/cljs/webmx

mxWeb proxy instances know which DOM element they represent, and because Matrix tracks change by property we have no need for VDOM or diffing: mxWeb knows exactly what to change.

2

u/yogthos Aug 11 '18 edited Aug 11 '18

Wouldn't it just be a matter of computing the data in chunks as in the example below, or am I missing something?

(defonce state (r/atom {:computed 0 :message ""}))
(defonce item-count (r/cursor state [:computed]))
(defonce message (r/cursor state [:message]))

(defn lazy-load [items]
  (swap! item-count + (reduce + (take 10 items)))
  (when-let [items (not-empty (drop 10 items))]
    (js/setTimeout lazy-load 0 items)))

(defn load-items []
  [:button
   {:on-click #(lazy-load (range 100000))}
   "load items"])

(defn display-computed []
  [:p @item-count])

(defn message-component []
  [:div
   [:input
   {:on-change #(reset! message (-> % .-target .-value))}]
   [:p @message]])

(defn home-page []
  [:div
   [display-computed]
   [load-items]
   [message-component]])

1

u/dustingetz Aug 11 '18

I may have explained the problem badly by focusing on the incremental state computation; the view patching also has to be incremental (e.g. now add 100k spans)

2

u/yogthos Aug 11 '18

That still works fine I think:

(defonce computed (r/atom []))

(defn lazy-load [items]
  (swap! computed conj (reduce + (take 2 items)))
  (when-let [items (not-empty (drop 2 items))]
    (js/setTimeout lazy-load 0 items)))

(defn load-items []
  [:button
   {:on-click #(lazy-load (range 100))}
   "load items"])

(defn item [x]
  [:span x])

(defn display-computed []
  [:div
   (for [x @computed] ^{:key x} [item x])])

(defn home-page []
  [:div
   [display-computed]
   [load-items]])

The item component will only be painted for new items as they're added, so you're not repainting the entire set of items as you're appending them.

3

u/dustingetz Aug 11 '18 edited Aug 11 '18

Click on it until you have N=100000 items, you're gonna slow down as N gets bigger. The jane street article on HN today explains it better than me

https://blog.janestreet.com/what-the-interns-have-wrought-2018/

2

u/kapitanfind-us Aug 11 '18

Off-topic.

That part of the post reminded me why I am not into static compilers anymore...I really was not able to understand what is the problem they are trying to optimize by looking at the API.

It seems they want to adopt a strategy that involves memoization/caching but are not thinking of garbage collecting?

Is this part of? I genuinely would like to know more.

2

u/dustingetz Aug 12 '18 edited Aug 12 '18

React.js gives us app-as-a-value (we build up big trees of virtual dom and diff against the previous one). That's really clever from an abstraction perspective but fundamentally slower than imperative solutions. Reagent is one way to try to get back directly targetted DOM updates, but it is state city with sneaky side effects, so it's easy but not simple (just try reading the source).

By Reagent is easy-but-not-simple, I mean a newbie can do a lot but as soon as you actually care about the performance of your app or try to build abstractions on top of reagent, the reactive abstraction leaks everywhere and you are in big trouble:

  • Takes great care to stabilize references and write fully reactive code (No lambdas for example, you have to write letfn so the reference is stable)

  • Function components aren't functions (for example, you aren't supposed to partial them, if you do so it will both leak memory and bust your reactions)

  • Reactions themselves aren't reactive - once a reaction fires, the whole chain is gonna fire, it doesn't memoize (maybe it can memoize though? We haven't tried to fork this yet)

  • Reaction evaluation order isn't deterministic – sometimes they will run in the wrong order and crash and reagent will rerun them

This is roughly my understanding. I may have gotten some details wrong, its not like this stuff is documented. We paid for this knowledge in blood.

Not clear to me where garbage collection fits in

3

u/chromalchemy Aug 12 '18 edited Aug 12 '18

Is Hoplon/Javelin any different than Reagent in these regards? To my (incomplete) knowledge:

  • Directly targeted DOM updates

  • Function components are functions

  • When a reaction fires, and a data cell is changed, only cells in the chain that depend on that data are recomputed. Not the entire chain.

  • Guarantees that cells are updated in the correct order, and only at most once

2

u/dustingetz Aug 12 '18 edited Aug 12 '18

Yeah! Definitely worthy of investigation and I know we've spoken about this before! Degoes: "The FRP model involves a huge graph of closures" – does this apply here? I don't know much about this.

The incremental model is appealing because the types are pure and compose in clear ways – so in theory it should compose to high complexity apps without sacrificing power or speed.

1

u/yogthos Aug 11 '18

There is going to be some overhead in checking the elements, but if you put println in the item component you'll see that only the new ones are actually painted. So, it scales pretty well in terms of DOM overhead as you're only painting new items. Most of the cost comes from recomputing the VDOM, and immutable data makes diffing relatively cheap. When I add the input field back in, it's still pretty responsive on my machine even once I have thousands of items painted.

I'm sure there are cases where the difference with the Jane Street approach becomes significant, but it seems like you'd have to have a fairly specific use case for this to become a problem in practice.

1

u/dustingetz Aug 11 '18

Lack of control over reagent reactions are, by far, the biggest source of performance problems in Hyperfiddle

1

u/jjttjj Aug 14 '18

It seems you are running into issues with reagent and that this is causing you to look at non-react solutions. I'm curious if you have considered at all some of the other react based solutions (rum or fulcro perhaps?) and if you have any insight into the relative performance and gotchas of these other options?

I've always been a hoplon person myself, but also am running into performance issues (which is a pain point for hoplon, probably more so than the react wrappers unfortunately) and am now trying to reexamine the cljs landscape a bit.

For me hoplon is kind of the holy grail in terms of offering a super high level, simple and easy to use interface. But sometimes I just want to be able to write my UI the same way when I'm dealing with things in my domain of size 5 and size 1000.

2

u/dustingetz Aug 14 '18

sometimes I just want to be able to write my UI the same way when I'm dealing with things in my domain of size 5 and size 1000.

This is the crux of it. I more or less understand the types in play for the incremental approach and am quite certain that it will scale to arbitrarily large next-gen applications of the 2020s without sacrificing power of abstraction (unlike the sneaky side effect solutions of today)

1

u/lilactown Aug 13 '18

It seems like this is something that would have to be implemented at the library-level to do it well, instead of in React.js user-land, unless you want to go the route of e.g. react-virtualized which already exists.

This means we'd have to create our own vdom implementation. I'd rather be able to leverage the whole React.js ecosystem than solve the 100k problem TBH.

In the future I can see this being improved in React.js itself, either as something that is solved behind the scenes or an extension of the API that could give us better options over what the behavior of the diffing is. The React.js team has been pretty vocal lately that they want us to entrust them with owning diffing and rendering, and I think they take that responsibility seriously. I'm not willing to bet against them.

I wonder if this could be ameliorated in some cases by using multiple roots, instead of a single app root. Obviously large lists wouldn't benefit (in that case, see react-windowed or react-virtualized), but extremely large & complex / less homogeneous apps might be able to take advantage of that.

1

u/dustingetz Aug 13 '18

I agree that the ecosystem effects can probably be bridged back in – incremental in the large, treeish in the small. In the large, I don't see how React.js can ever do this because the incremental architecture does not use diffing at all, nor is incremental compatible with local state i think.

1

u/dustingetz Aug 13 '18

For example, in the large, Reagent bypasses React.js diffing entirely, relying wholly on forceupdate (except for the non-reactive parts of your app, and it is quite unfortunate that Reagent apps are only partially reactive, never fully reactive). But in widget land, Reagent can use React.js widgets perfectly.

1

u/lilactown Aug 13 '18

This is why I'm looking to move away from reagent though; I'd prefer to leverage React.js better, not work around it. FRP and React.js are simply not friendly to each other in the large. Things like suspense and React.js' async rendering are going to be in conflict with the way reagent works internally.

I've come to the conclusion that the way many CLJS libs (and certain JS state management libs like MobX) subvert the way React.js controls their app will cause us to lose out on a lot of developments in the general React.js ecosystem.

Ninja edit: which is to say, I'd rather (if possible) see it the other way around: tree in the large, incremental in the small where the performance characteristics of our app require it and we're willing to make that tradeoff in loss of functionality and more ownership of the whole render process.

1

u/dustingetz Aug 13 '18

React.js tree pruning model isn't fast enough for anybody though – consider a simple CRUD app where any transaction can cause data anywhere on the page to update – the entire view has to re-render in this case, tree-pruning can't help. This is why Om Next has indexer/reconciler, Reagent has reactions, Redux has "connect" and React itself has setState/forceUpdate. I use Reagent in anger because I don't know a better way (and then make reddit threads like this lol)

2

u/lilactown Aug 13 '18

Now I'm not sure what you're saying exactly.

I'm saying that we should endeavor not to circumvent what is in React.js proper. React.js has both setState and context, which allow leaves to listen to state changes and re-render independently of other leaves. It seems better to use those tools (perhaps more ergonomic wrappers around them) than to route around them and take more control of your app, unless you absolutely need it.

2

u/lilactown Aug 13 '18

If diffing the VDOM is also causing a huge slowdown, I could imagine an API that allows you to opt-in to different diffing characteristics. E.g. to be able to set a specific branch as a separate "root" that will not be considered in any diffs of other parts of the tree, and perhaps could be controlled differently, without forcing the entire app to make that tradeoff.

3

u/mklappstuhl Aug 11 '18 edited Aug 16 '18

Interesting observations. Just from the name-similarity - I’ve always wanted to explore google’s incremental DOM more https://github.com/google/incremental-dom

Will also be interesting to see how those new approaches will be able to support reacts component model whose - imho biggest - innovation is introducing some indirection between code and rendering target (see PDF, Sketch, WebGL, VR/AR and all kinds of other “extensions”)