19 ms·
Virtual DOM is pure overhead (2018)
- deleted 8y ago[deleted]
- saggas 8y agoI have never used modern JS frameworks like Angular, React and Vue and I have always assumed (hoped) that they contained optimisations that you would be unlikely to use in your vanilla JS code even though you could. Something like FastDOM which batches read/write operations to avoid unnecessary reflows. Do they contain anything like that?
- xtagon 8y agoI'm not sure if this is exactly what you mean, but Ember.js has a concept called a "runloop" which batches different actions into queues, which does seem to help with rendering/reflows.
- zeugmasyllepsis 8y agoTo varying degrees depending on the library, I believe the answer is "yes, they sometimes do". Angular and Ember at least have systems for batching user interactions, which translate into model updates, and thus potentially DOM updates. I believe the respective systems for handling this are called Zone and Backburner for Angular and Ember, but I've been out of touch with those projects for a couple of years. There's definitely a trade-off, however. They make a huge difference for noisy events (like mouse move, scrolling, dragging, etc), but tend to make debugging much harder in my experience. When things go wrong, the stack traces nest deeply into the event handling systems and code paths no longer resemble the relatively straightforward world of traditional event calls, where a callback handler is invoked directly in response to a single event.
- kevingadd 8y agoVirtual DOM is a shaky long term bet since it's essentially betting that the cost of DOM operations will always be high enough to justify all the work you're doing (both at runtime and at trying-to-figure-out-how-to-write-this-code time). When it's easy to do your virtualization, you can just go 'well this is an optimization i can remove at any point', but if it's suddenly so complex it introduces bugs, you're in trouble. Naturally, the cost of DOM operations didn't go unnoticed and while people have been going in on virtual dom solutions like React, the devs of Firefox, Chrome and Safari have all been aggressively optimizing the dom - making the native code bits faster and moving more of the DOM into javascript so all your JS can get inlined and optimized. It gets harder and harder for libraries to compete with regular DOM as a result.
- striking 8y agoreact-dom (https://github.com/facebook/react/tree/master/packages/react-dom https://github.com/facebook/react/tree/master/packages/react...) is shipped as a dep of react, and seems to be where all the heavy lifting is. I believe that, should DOM ops become fast enough that you don't need vDOM anymore, you could easily no-op all of this out with direct DOM calls.
- mantap 8y agoSurely JS engines are also optimising React-style code. e.g. the article says that react style code does a lot of unnecessary object creation (e.g. map) but if that is now a common pattern then JS engines can do a lot to optimise that away.
- kevingadd 8y agoYou can optimize the unnecessary operations but it's a lot more work to fully determine that they're unnecessary and erase them.
- addicted 8y agoWell, you could also potentially have a future where the VDom is the primary Dom in itself. As in, the VDom doesn’t need to be converted to HTML for the browser to render, but rather, the browser directly converts the VDom objects into Pixels.
- pier25 8y agoThe cost of the DOM operation is the same. The difference is that React batches the changes to reduce the number of operations whenever possible.
- Sawamara 8y agoEw, not really. Even the getters can be performance-heavy in DOM-land. If you store your data in JS-land, and only diff against that, you never need to touch the dom for anything, except the endpoint insertions. At worst, it is matched evenly by any sort of custom vanillaJS+Dom manipulation tool (which needs to be perfectly well written, and hand-crafted to match what you are currently working on). At best, its several orders of magnitudes faster compared to a badly written DOM-manipulation-heavy code.
- spankalee 8y agoThis is absolutely true. Virtual DOM diffs do a huge amount of unneeded work because in the vast majority of cases a renderer does not need to morph between two arbitrary DOM trees, it needs to update a DOM tree according to a predefined structure, and the developer has already described this structure in their template code! A large portion of JSX expressions are static, and renderers should never waste the time to diff them. The dynamic portions are clearly denoted by expression delimiters, and any change detection should be limited to those dynamic locations. This realization is one of the reasons for the design of lit-html. lit-html has an almost 1-to-1 correspondence with JSX, but by utilizing the static/dynamic split it doesn't have to do VDOM diffs. You still have UI = f(data), UI as value, and the full power of JavaScript, but no diff overhead and standard syntax that clearly separates static and dynamic parts. The syntax is very close: JSX: render(props) { return <> <h1>Hello {props.name}</h1> {props.items ? <ol>{props.items.map((item) => <li>{item.label}</li>)} </ol> : <p>No Items</p>} </>; } lit-html: render(props) { return html` <h1>Hello ${props.name}</h1> ${props.items ? html`<ol>${props.items.map((item) => html`<li>${item.label}</li>`)} </ol>` : html`<p>No Items</p>`} `; } I really think the future is not VDOM, but more efficient systems, and hopefully new proposals like Template Instantiation can advance and let the browser handle most of the DOM updates natively. edit: closed JSX fragment as pointed out
- foobarbecue 8y agoTypo -- you didn't close your fragment on the JSX.
- ec109685 8y agoOne thing nice about React is that it can take care of quoting for you depending on the method call the jsx template translates into (attribute, value, element name). String templates doesn’t have that nice property.
- spankalee 8y agoCan you explain that more? I'm not sure what you're saying is true with lit-html. You don't have to quote attributes with single expressions. html`<div class=${myClass}></div>` is perfectly fine.
- xtagon 8y agoSvelte's philosophy on turning the virtual DOM concept inside out sounds like it has merit, and is very promising. But it's going to take a lot more than that, in my opinion, before a large number of people consider switching from React, Ember, etc. I don't see that as a drawback, I see it as an open opportunity for Svelte to keep building out on improvements other than the DOM updates, and catching up with everything else the SPA alternatives provide that have nothing to do with the virtual DOM. For example, Ember is just a joy to work with, and makes it easy to rapidly prototype reactive frontends in a way that reminds me of Ruby on Rails's initial appeal to developer happiness, and the tooling is very mature. If you could unlock all those benefits while keeping the blazing fast DOM updates, oh boy!
- hatch_q 8y agoTooling is the key word here. Svelte simply doesn't have the tooling needed for any big project. - testing/testability (unit-tests are easy, but what about functional, e2e?) - strong-typing support (flow, typescript) - good IDE support? - i18n? ICU support, etc? They need to redo what ember-intl or react-intl do. Without these things it's simply not viable to start bigger projects with new framework.
- deleted 8y ago[deleted]
- nemothekid 8y agoVirtual DOM is pure overhead* * Compared to doing static analysis and optimizing your UI updates at build time. While I certainly agree that svelte's approach may be the future, I think React and others, are very much a needed stepping stone (especially when you consider all the work done transpiling JS code). The Virtual DOM was the most performant solution that applied generally to many a large number of cases. The reason almost everyone did `x.innerHtml = html` is that it was the most general and widely available solution.
- floatboth 8y agoNo, you don't need to do anything at build time! (You don't even have to have a build time.) You can just… instantiate a template, remembering where the "holes" are, to get precise update functions for every data field that gets inserted into the template. This is what lit-html does, and it's such an obvious approach I'm really surprised that VDOM took off before it. https://lit-element.polymer-project.org https://lit-element.polymer-project.org
- Lowkeyloki 8y agoFirst, I think anyone using React solely because of the virtual DOM implementation is largely missing the point. IMHO, the real win of React is the functional and composable way components can be designed and implemented. Second, no disrespect to Svelte, but I think there's a huge trade-off between the React approach and the Svelte approach that developers should be aware of. React is a pretty unopinionated library, all things considered. The only compilation step necessary is JSX to Javascript. JSX maps pretty directly to React's API. This means compilation is pretty simple. So much so that you can do it by hand really easily if you really wanted to. Svelte, on the other hand, is pretty compilation-heavy. There's a lot of what I'd consider to be non-trivial transformation going on between the code you pass to the Svelte compiler and what comes out of it and runs in the browser. Personally, I'm less comfortable with that compared to React's runtime library approach. But if you are comfortable with that trade-off, that's perfectly fine. It is worth being aware of it, though.
- kabes 8y agoVirtual dom is an implementation decision for performance a developer shouldn't even be very aware of. The main upside to react is that it has a huge ecosystem.
- Waterluvian 8y agoYou should at least be aware of the gist, lest you obsess over premature optimization. 1. Changes to the DOM cost a ton more than executing JS code. 2. So don't feel too bad when a render() gets called that doesn't change anything because the virtual DOM swallows that.
- spankalee 8y ago> 1. Changes to the DOM cost a ton more than executing JS code. The point of the article, and of the performance problems that people actually have with React is that this might be true for a small number of JS operations, but that 1) Tree diffs are computationally complex operations that add up for real-sized apps 2) The diff is actually unnecessary if you simply take into account the structure of templates, so diffs are pure overhead. So _do_ feel bad when you have a no-op render() in React at least, because the resulting VDOM diff just chewed up CPU and battery for no reason.
- thoman23 8y ago2 things I'm not seeing in the article or in the comments so far: 1) The virtual DOM is an abstraction that allows rendering to multiple view implementations. The virtual DOM can be rendered to the browser, native phone UI, or to the desktop. 2) The virtual DOM can, and should, be built with immutable objects which enables very quick reference checks during the change detection cycle.
- spankalee 8y agoThere are other ways to represent a UI as data that don't require a diff. JSX's default compiler output throws away information needed to do efficient updates, and instead requires diffing the entire old and new trees. Immutable objects may optimize for checking for data changes, but only if you do that, as in shouldComponentUpdate or checking inside render(). They don't optimize the _diff_, which is done against the DOM.
- keymone 8y agoHow often is diff done against the DOM? My understanding is that it’s done against last valid vDOM instead.
- spankalee 8y agoSorry, you're correct for React, and for most VDOMs, though some do diff against the DOM. The point is that the diff isn't sped up by using immutable data. The app data is only used to generate the vdom tree, and the diff is after that.
- kgwxd 8y agoOn point #2, ClojureScript not only provides immutability out of the box, but also has libraries for replacing JSX with the same stuff everything else is built with. It's an insanely beautiful way to work with React.
- city41 8y agoReagent is probably the best UI dev experience I’ve found yet. A quick blog post explaining why for anyone curious about reagent: https://www.mattgreer.org/articles/reagent-rocks/ https://www.mattgreer.org/articles/reagent-rocks/
- guscost 8y agoFrom the conclusion: > Virtual DOM is valuable because it allows you to build apps without thinking about state transitions, with performance that is generally good enough. In other words, Virtual DOM is somewhat-valuable overhead. This is a cool alternative, seemingly sort of a compile-time version of Knockout. It's probably worth a try for writing an efficient client app, but I have a hunch that I'd miss the "HTML-in-JS(X)" pattern if I went back to using "JS(?)-in-HTML" instead. A VDOM runtime allows you to write plain JS that "just works", at least until certain parts need to run faster. This means junior programmers can pick it up and become productive quickly, and avoid driving their projects off a metaphorical cliff. Of course this is bought with bandwidth and CPU overhead, lots of it in some cases. The call you should make when considering a VDOM is whether the safety and familiarity benefits are worth the overhead. If your team is experienced enough to take on a new DSL for rendering markup (which every template-binding tool really is) and meticulous enough to assign instead of mutate and avoid two-way binding pitfalls, go for it. If not, be careful. This is not meant as a challenge. Personally I wouldn't want to work on a big application that is wholesale optimized in this way, unless there was no alternative. I wouldn't write my own game engine (if it was for a job) either.
- floatboth 8y agoYou can easily do HTML-in-JS "react-like" rendering without diffing! lit does just that https://lit-element.polymer-project.org https://lit-element.polymer-project.org
- namelosw 8y agoI thought this was well known years ago. A better description for VDOM should be 'It's not fast, and is not slow either'. But frankly, what I see in virtual DOM is not about speed. It's a declarative interface, an abstraction. It's more like a blueprint that's easier to interpret across different environments like React Native, WebGL. Even if you don't need any of these cross-platform benefits it's still good for testing -- without real DOM. As for performance, it could be an aspect of advertising but I doubt it really matters anymore. I saw many applications where AngularJS is too slow, and I even worked on one for quite a while -- it's just a fairly typical 'enterprise application'. But I still yet to see a real-world front-end project where React is too slow. Users won't even care about if it is 10ms or 30ms.
- Rusky 8y agoThe point of the article is that you can get that same declarative interface at much lower cost, with a more efficient implementation.
- namelosw 8y agoI'm not sure if it's still an 'interface' since it's compiling another language to imperative code which operates DOM API. So it requires other platforms implements a similar imperative API surface as DOM.
- awesomepeter 8y agoWhich is the same thing that a virtual DOM does, it also has to have an adapter(react-dom in Reacts case) which applies the VDOM to the real DOM via it's imperative API.
- Bahamut 8y agoI work on one with React that is too slow in the browser with a team that only has senior devs, and users even filed bugs about the performance - we do heavy computations, and React's model of blocking rendering on having everything updated can freeze our UI for up to 10s while data comes in from various API requests. I believe our app would be performing much better for the end user if we were using Angular 2+ interestingly enough due to its built in incremental updating - there would be other tradeoffs though. Part of the problem is not having good enough APIs currently (we have to make too many API requests and data payloads are too fat, sometimes up to 2 MB per request), but imperfect APIs tend to be the case in a lot of apps early in their lifecycle. I've actually been a bit disappointed in React's performance from a UX perspective.
- computerex 8y agoWhat a strange post. Yes, virtual DOM is overhead, much like JIT compilation is an "overhead". But this overhead ultimately translates to better performance because many virtual DOM transformations can be buffered into 1 transformation of the real DOM.
- Rusky 8y agoBetter performance than completely recreating the DOM, sure. But all the time spent constructing and diffing the virtual DOM is pure overhead compared to simply doing that 1 real transformation directly.
- azangru 8y ago> ultimately translates to better performance Better compared to what? For a library like React, which re-renders the DOM tree every time component’s props or state change, virtual DOM with diffing and patching is indeed a better approach as compared to naive re-rendering of the whole DOM. But as Rich Harris said during his talk about Svelte v.3.0, whenever he hears claims about better performance of frameworks based on virtual DOM, illustrated with benchmarks, he runs the same benchmarks with Svelte (not based on virtual DOM), and inevitably gets better results.
- nemothekid 8y ago>But as Rich Harris said during his talk about Svelte v.3.0, whenever he hears claims about better performance of frameworks based on virtual DOM, illustrated with benchmarks, he runs the same benchmarks with Svelte (not based on virtual DOM), and inevitably gets better results. That isn't a fair comparison. Consider this analogy - React is the JVM and Svelte is Rust. JS before either is C. Now it can be shown that in most cases that C is faster than anything on JVM, but in reality it wasn't, and that C code was riddled with bugs. The JIT'd JVM comes a long and guarantees safer and more performance code. Then someone comes a long and says the JIT is overhead rewrites everything in Rust and shows how fast the program is. What's being ignored is the man-years, technology and insights that made Rust possible. The fact of the matter is, (1) code that is written like Svelte generates was incredibly rare and difficult to achieve and (2) Svelte is pretty radical in how the framework is implemented (at a high level, Svelte is essentially doing static analysis on your code to figure out where the DOM is being updated, serving a like-minding purpose of Rust's borrow checker).
- ummonk 8y ago>The danger of defaulting to doing unnecessary work, even if that work is trivial, is that your app will eventually succumb to 'death by a thousand cuts' with no clear bottleneck to aim at once it's time to optimise. This is so true in practice.
- ng12 8y agoI keep hearing this and find it really hard to care about. Runtime performance is not a bottleneck for me. Once in a blue moon I'll have to optimize a React component with shouldComponentUpdate but otherwise I have no performance concerns even on old browsers. There are other characteristics that are very, very important like build size. VDOM is not worth thinking about. Honestly I don't understand Svelte. It sounds like it's very good at the things it does but the things it does are not the things I need.
- dsissitka 8y agoIf you value build size you might want to take another look at Svelte. Build size is one of its strengths. For example, the Svelte implementation of RealWorld is roughly 10% of the size of the React/MobX implementation: https://medium.freecodecamp.org/a-realworld-comparison-of-front-end-frameworks-with-benchmarks-2019-update-4be0d3c78075 https://medium.freecodecamp.org/a-realworld-comparison-of-fr... Edit: Confused the React/Redux implementation with the React/MobX implementation the first time around.
- JMTQp8lwXL 8y agoTo my understanding, one of (or the singular) author of Svelte was a developer for the NY Times who wanted to easily create visualizations with thousands of data points, and the existing UI libraries weren't cutting it on performance. Depending on the types of applications you build day-to-day, this problem space might be niche. Your standard CRUD app (tables, forms, etc) would not be leveraging Svelete's capabilities; in a sense, it could be a pre-mature optimization.
- ralphstodomingo 8y agoI feel as if Svelte came at the wrong time. These days, when most people know either React or Vue or some other thing, and computing devices are performing better over time, there's diminishing returns on performance optimization. Sure, you do a bit of it, and then you're often better doing something else, like enhancing developer experience for example. I really like the idea, and will play around with it, but fat chance it's getting into production with me. I am much more productive with React now, and I worry more about business requirements than raw performance (that I almost never worry about these days).
- osrec 8y agoWe implemented a library at my company that does not use a virtual DOM, but instead captures reactive "change functions". The framework captures dependencies between the reactive "change functions" and underlying variables, and executes the functions whenever a variable's value changes. You can also have dependencies between variables (like computed vars in Vue), and the lib works out the correct order for calculation and execution. All the change functions get queued up and applied in order before the next repaint. Everything is component based, and there is even a nice kind of inheritance (with lazy, async component loading). It works rather well. I'd be happy to share it with anyone that's interested! Not open sourcing it yet, as I envisage it would be a full time job to support it! Edit: the upside of the change functions is that YOU decide how the DOM is updated. It's really quite cool to be able to implement a function like the following and have it run to update this.$dateOfBirth whenever this.data.dateOfBirth changes: function() { this.$dateOfBirth.val(this.data.dateOfBirth); } That is of course a simple example, but when you need even more control, reactive change functions have proven to be super useful (for us anyway!).
- markharper 8y agoThat sounds similar to the incremental lambda calculus described in this paper: https://arxiv.org/abs/1312.0658 https://arxiv.org/abs/1312.0658 There's an implementation for DOM updates in Purescript (https://blog.functorial.com/posts/2018-04-08-Incrementally-Improving-The-DOM.html https://blog.functorial.com/posts/2018-04-08-Incrementally-I...), but I haven't come across a similar approach in Javascript yet.
- osrec 8y agoYes, it's a similar idea. The only difference I can see is that in our library, the dependencies are automatically tracked, and there is some additional clever scheduling around when a function should be run.
- wnevets 8y agoI remember when react was new and the reason why everyone should use it was because of its virtual dom and lack of typescript. Now everyone is saying the virtual dom isn't the point and advocating typescript.
- ec109685 8y agoSeriously, who actually said lack of typescript was a plus for React ever? That seems like a non-sequitur.
- wnevets 8y agoA lot of people back when every blog was comparing Angular (read not angularjs) and Reactjs.
- preommr 8y agoPeople were upset about being FORCED to use typescript. It was hard for some people to accept both being bundled together. Not to mention I would say this is before when typescript had even less support and there was a chance it was going to be like coffeescript. Hell typescript adoption is still pretty low according to metrics like the TIOBE index (although that doesn't mean much).
- QuadrupleA 8y agoSo glad to see this article, I've long wondered how this "virtual DOM is faster" myth got accepted as gospel when clearly it's pure overhead, compared to a well written app that updates the DOM directly only when needed (which I find is easy to accomplish in most apps). Can't speak to the svelte approach due to inexperience with it, but good to see this myth challenged - react.js is fine but I worry there's been a cargo cult mentality around it, that it's The One True Modern Way To Do Web Apps, when really it's a tradeoff that involves some extra layers and performance baggage, and like any tool you need to weigh the pros and cons.
- andrewfromx 8y agotell me about it! Or, heaven forbid, just make the user get the entire html page rendered from server after every click like it's 2003 or 2004!
- muxator 8y agoWhich sometimes is not bad at all. Ever tried to ctrl-click an interface element (a navigation button, a menu) because you want to open its view in a new window? A lot of (admittedly badly coded) "modern" web apps ignore basic web idioms (like hyperlinks) and assume as unique single user workflow the one its designer tought the app (and the only one he tested).
- the_duke 8y agoA nice example of this: with the new Reddit interface, only visible comments are rendered, so you can't use your browser search functionality to search all comments on the page, just the ones currently in the viewport.
- folkhack 8y agoAmen to this. The new Reddit interface is a step backwards in functionality due to this sorta stuff and effectively breaks user experience. Just to give an idea how bad it is: loading the front page cold of new reddit = 9685KB. Loading the front page on the old reddit (also cold) = 737KB. The compute profile is literally half for old.reddit.com (new peak 16%, old peak 7.5% - both metrics core-distributed over an 8c system; 1s sample rate). I LOVE all of this talk that front-end devs like to have on optimization/state stability. Talk to an browser automation expert, esp. one that does it at scale. Almost 100% of the time older/simpler front-end tooling/development is faster and less error prone. Older also takes a FRACTION of the compute/memory/proxy resources. It's been this way for years!!! ducks for the inevitable storm of HN hate for having a strong opinion
- revskill 8y agoTo me, React is more about Developer Experience. The ease to reason about the app is far much more important than anything else. The problem with Svelte, is that, it sounds "words louder than action". You can learn from React documentation. Instead of throwing a bunch of concept to the dev face, it brings out the WHY of ReactJS with real code. Teaching users right from documentation is the best way to introduce a library/framework for user to really experience with the tech.
- rahimnathwani 8y agoIf you like the React documentation with real code examples, you'll love the Svelte tutorial with both code examples and a live playground. The UI is beautiful, too: https://svelte.dev/tutorial/basics https://svelte.dev/tutorial/basics The examples are also very clear: https://svelte.dev/examples#hello-world https://svelte.dev/examples#hello-world
- reilly3000 8y agoHas anybody here migrated a UI from React to Svelte? How did it go?
- ru999gol 8y agoof course not, this is just opinionated rubbish, in the real world people use react dom/native
- PudgePacket 8y ago> Be kind. Don't be snarky. Comments should get more thoughtful and substantive, not less, as a topic gets more divisive. https://news.ycombinator.com/newsguidelines.html https://news.ycombinator.com/newsguidelines.html https://mobile.twitter.com/sveltejs/status/1088500539640418304 https://mobile.twitter.com/sveltejs/status/10885005396404183...
- paulddraper 8y agoI quote an Angular contributor > If you call something "view" and diff it, then it's Virtual DOM. > If you call something "view model" and diff it, then it's Dirty checking. (Angular uses the latter.) https://github.com/angular/angular/issues/22587#issuecomment-370420631 https://github.com/angular/angular/issues/22587#issuecomment...
- Lx1oG-AWb6h_ZG0 8y agoDan Abramov has a great thread about this here: https://mobile.twitter.com/dan_abramov/status/1120971795425832961 https://mobile.twitter.com/dan_abramov/status/11209717954258.... In particular, I find this argument really persuasive: > Time slicing keeps React responsive while it runs your code. Your code isn’t just DOM updates or “diffing”. It’s any JS logic you do in your components! Sometimes you gotta calculate things. No framework can magically speed up arbitrary code. In my experience, as your app grows, the amount of time you spend on dom reconciliation becomes negligible compared to your own business logic. In this case, having a framework like React (especially with concurrent mode) will really help improve perceived user experience over a naive compiled implementation.
- tylerhou 8y ago> In my experience, as your app grows, the amount of time you spend on dom reconciliation becomes negligible compared to your own business logic. In this case, having a framework like React (especially with concurrent mode) will really help improve perceived user experience over a naive compiled implementation. In my experience, the exact opposite occurs. If there is ever any heavy computation I need to do, I usually try spawn a web worker or offload it to the server. In contrast, as your app tree grows reconciliation costs grow (super?)linearly, and more importantly there is (currently) no way to offload reconciliation.
- dmix 8y agoSame, the only time I've run into performance issues with Vue after building many very complex deeply nested components prior to this was one which ground to a halt on re-rendering because I was simply rendering too many elements into the DOM with their subsequent watchers filling up memory. After hours of combing through frames of the memory profiler and seeing only highly concurrent framework calls the only solution was to paginate the particular content. 99% of the users never had this issue but it was 1-2 customers who had thousands of components to render instead of the usual hundreds. I'm really curious now if Svelte would have helped with that because it was a huge dev timesink and one where I was never satisfied with the solution. As it really should be able to render that amount of data. It obviously wasn't a problem in the jQuery/Rails version I was replacing and improving upon (although page load times was higher). The new React concurrency model wouldn't have helped from what I've read. I just needed something lighter weight from the rendering model itself. Vue 3.0 is apparently going to come with plenty of performance improvements so I'm looking forward to that as well.
- oraphalous 8y agoI think this article - and many of the comments on this thread are forgetting the context of how DOM manipulation was typically done when the virtual DOM approach was introduced. Here's the gist of how folks would often update an element. You'd subscribe to events on the root element of your component. And if your component is of any complexity at all - first thing you'd probably do is ask jQuery to go find any child elements that need updating - inspecting the DOM in various ways so as to determine the component's current state. If your component needed to affect components higher up, or sibling to the current instance - then your application is often doing a search of the DOM to find the nodes.. and yes if you architect things well then you could avoid a lot of these - but let's face it, front end developers weren't typically renown for their application architecture skills. In short - the DOM was often used to store state. And this just isn't a very efficient approach. This is what I understood the claim that VDOMs are faster than the real DOM meant - and the article is pretty much eliding this detail. As far as I'm aware React and its VDOM approach was the framework that deserves the credit for changing the culture of how we thought about state management on the frontend. That newer frameworks have been able to build upon this core insight - in ways that are even more efficient than the VDOM approach is great - but they should pay homage to that original insight and change in perspective React made possible. I feel this article and many of the comments here so far - fail to do that - and worse, seem to be trying to present React's claim of the VDOM faster than the DOM as some kind of toddler mistake.
- toasterlovin 8y agoNot really a JS developer, but from my recollection, everything you said is essentially correct. I was on the periphery of the Ember community when React dropped. I remember a blog post or something where the Ember developers basically acknowledged that React's virtual DOM approach was significantly more performant than what Ember was doing and, to the Ember community's credit, resolved to re-architect their view rendering layer to shrink the performance gap.
- karmelapple 8y agoThat is indeed what happened, and Ember got some major performance enhancements as a result! Things like Glimmer were a result of this.
- EGreg 8y agoI have always said: Angular is diffing the model React is diffing the view That’s all. Better to just skip the diffing usually, and grab references to elements and update them when certain events happen. It’s really ok!
- quickthrower2 8y agoThe problem is spaghetti! You have something in the Dom and you might not know what can or has updated it or why...
- EGreg 7y agoWhen everything is event based, you know. You can trivially even record the entire call stack on an object attached to the DOM element, when your framework is in debug mode. You can see the whole history of call stacks if you so choose. And there is no waste, either.
- floatboth 8y agohttps://lit-element.polymer-project.org https://lit-element.polymer-project.org lit-html essentially grabs references to elements automatically when parsing a template. You get react-like rendering without any diffing! And does not require build tools.
- smith-kyle 8y ago> Here, we're generating a new array of virtual <li> elements — each with their own inline event handler — on every state change, regardless of whether props.items has changed. Unless you're unhealthily obsessed with performance, you're not going to optimise that. React makes it pretty trivial to prevent rerenders when props have not changed
- pier25 8y agoAfter years of doing mostly React and Vue SPAs I've never experienced a performance problem. The metrics of Svelte that interest me more are lines of code and bundle size, both in which it excels. Here is an article that compares the exact same project called RealWorld written in a number of front end libraries/frameworks. https://medium.freecodecamp.org/a-realworld-comparison-of-front-end-frameworks-with-benchmarks-2019-update-4be0d3c78075 https://medium.freecodecamp.org/a-realworld-comparison-of-fr... Here is the main repo for the RealWorld project for front and backend: https://github.com/gothinkster/realworld https://github.com/gothinkster/realworld
- pan_4321 8y agoSame experience here but with React and Angular (2+). No real world differences that can be observed by an average user in the average app. The choice has to be made by ecosystem, programming style, etc. React as a library offers not enough for me personally. Angular is too heavy on concepts. Vue seems to hit the sweet spot?
- underwater 8y ago> The original promise of React was that you could re-render your entire app on every single state change without worrying about performance. In practice, I don't think that's turned out to be accurate. If it was, there'd be no need for optimisations like shouldComponentUpdate (which is a way of telling React when it can safely skip a component). It's shouldComponentUpdate(), not shouldDOMUpdate(). Even if DOM operations are direct, or the virtual DOM is infinitely fast, there are plenty of situations where you want to avoid running application code on every update. Some frameworks use data binding to track if a component update is necessary. This is what Svelte does, but because there is no explicit checks they have some weird conventions around annotating certain bound values: <script> export let num; $: squared = num * num; </script> React just happens to implement this behaviour different: it assumes a component needs updating unless the shouldComponentUpdate() hook says otherwise. The advantage (ironically) is that React is "just JavaScript", whereas Svelte needs a compiler that can instrument the code. This design decision shouldn't be confusing to the author; I assume he would have made this design decision consciously?
- JMTQp8lwXL 8y agoWell-written React code shouldn't need to leverage the shouldComponentUpdate API. The application structure would be off, if that's the case.
- underwater 8y agoA React component can do arbitrary, computationally expensive, logic inside components. React gives you the ability to memoize that work. Without shouldComponentUpdate developers would need to hand roll a caching layer or stick computed values in a store.
- prashnts 8y agoWith the current release, you can use a hook, such as `useMemo`, which would memoize the value for the entire lifecycle of your component. I’ve been writing in react for around 3 years now, and never had to use shouldComponentUpdate, but instead compute whatever needed either on mount or when props changed. Curious what prompted the case you mentioned?
- deleted 8y ago[deleted]
- rayiner 8y agoOnly ever having used MFC and Swing, this seems odd to me. A diff of the entire DOM on every state change? You never see anything like that in native toolkits. ELI5: What problem is that solving?
- adamnemecek 8y agoMakes programming somewhat easier and also batches layouts.
- Tehdasi 8y agoThe problem it's solving is the DOM being unsuited to writing the kind of applications that MFC and Swing are used for writing. (which, for the web, is a SPA)
- andrekandre 8y agoisn’t this pointing to more of a fundamental problem with how browsers/html/document model are designed/implemented than anything else? html was originally a document format, not an app framework, and i think all of these frameworks (large and small) are just workarounds when what we really need is a fundamental re-imagining of what the browser should/could be. sometimes i wonder if alan kay was right when he said the browser should have been basically just byte-code interpreter[1]... [1] http://www.drdobbs.com/architecture-and-design/interview-with-alan-kay/240003442?pgno=2 http://www.drdobbs.com/architecture-and-design/interview-wit...
- tptacek 8y agoYou write your UI declaratively, in almost straight-line code, and never "update" anything in the UI itself. It's significantly easier to write.
- deleted 7y ago[deleted]
- nojvek 8y agoThe ideas of svelte are great. It reminds me of snabbdom thunks and inferno blueprints. If you know the view code ahead of time, you could do plenty of perf optimizations since you exactly what changes and what to react to. But sometimes I dynamically generate vdom nodes. Like markdown to vdom. There vdom shines. It’s a simple elegant idea. I think svelte is exaggerating a bit. React and vdom family of libraries are great. Svelte is great too. Not mutually exclusive. Someone should write a Babel jsx transpiler that does svelte like compile time optimizations for react. At the same time still allows dynamic runtime diffing if needed. No reason why we can’t have best of both worlds.
- acemarke 8y agoThe React team (and other parts of Facebook) _was_ working on a project along those lines called "Prepack": https://prepack.io/ https://prepack.io/ I think work on that has slowed for the time being, but it's got some interesting possibilities.
- fnordsensei 8y agoI do this with React all the time as well, though via ClojureScript and Re-frame[1], in which nodes are represented as plain Clojure data structures. E.g., send an article from the server, formatted in EDN/Hiccup[2][3]. Insert it into a component in the frontend, and it's converted to VDOM nodes. No further logic or conversion required. [1]: https://github.com/Day8/re-frame https://github.com/Day8/re-frame [2]: https://github.com/edn-format/edn https://github.com/edn-format/edn [3]: https://github.com/weavejester/hiccup/wiki/Syntax https://github.com/weavejester/hiccup/wiki/Syntax
- palerdot 8y agoI just noticed that Reframe README is very amusing and wickedly hilarious in some parts. It is very refreshing to read compared to other bland/formal/techinical READMEs ... Maybe in future I will try and see if using Reframe itself is joyful like its Readme ...
- fnordsensei 8y ago
- gigatexal 8y agoSeems plausible to me but the examples don’t work on mobile (iPhone iOS 12.3 with safari) nor is the layout mobile friendly at least when render in portrait modes on my phone.
- kyberias 8y agoPlease God let me never get into a situation where I need use these frameworks.
- franciscop 8y agoSeems like just an ad for Svelte, and fairly FUD-ish on that. React will warn you by default when doing that exact example, asking you to provide a key to the `<li>` to avoid re-rendering it unnecesarily. Instead, this states "Unless you're unhealthily obsessed with performance, you're not going to optimise that."
- lenkite 8y agoPersonally, I find modern template based approaches like lit-html, hyperhtml/lighterhtml better and faster. And also being far, far smaller. Throw in a CSS framework like bulma or tailwind-css and you are good to go at a smaller footprint and better performance.
- floatboth 8y agoAnd lit works without any build tools!
- nsonha 8y agothe main reason templates are bad is not that it needs a build step, it's more about being non-standard (a problem lit-html doesn't have), and not statically analyzable (think typescript's jsx), which lit-html doesn't solve.
- lenkite 8y agoWeb Templates support slots and are analyzed at definition time. All this is native code supported by the browser so big heavy JS doesn't need go be sent across the network and then run even more slowly in order to produce HTML. All web-template based libraries beat React/Angular/any VDOM based alternative in performance and footprint.
- nsonha 7y ago"...support slots and are analyzed at definition time" I don't know what you meant by this. As we speak, is there a standard implementation of this "Web Templates" thing? Can I open an editor, type "native" html, incorrectly assign to some attribute some callback with the wrong type and the editor tells me it's wrong without running the website? As for "ALL web-template based libraries beat React...", is there evidence to substantiate such claim? Surely SOME of them are not that performant. Also slots exist in most frameworks including Angular and in various 3rd packages in the React ecosystem.
- 7y ago
- Sawamara 8y agoI was running some quite complex UI systems in several of my projects with vanillaJS, cached DOM elements, all that jazz. Nothing like VDOM. Then eventually, it started to finally bog me down. Like rendering an inventory in an RPG system where you can buy stuff from the vendors: I started to get dissatisfied with change operations that lasted upwards to 2-3ms in a bad day. Then I started caching even more DOM elements, and started to build local data structures to see which was rendered last,and to what, to avoid rerendering everything, and to optimize to the change-based render only. A few weeks of this, and it dawned on me that had I needed to generalize my solution, I would have arrived at the exacty same model that hyperscript does for its diffing, and something similar to whats underneath React's diffing method (or Preact since I prefer that, but they share the API). So yeah, virtual dom is just a more clever and straightforward way to map your state to the dom, identifyng exactly where the changes happened, and only updating those nodes, instead of doing any queries towards the dom api (costly, can cause rerender,like when checking for bounding boxes, etc). It IS more useful because you no longer need to maintain a hyper-specific update function per project and manuallí created/maintained differs.
- Mikushi 8y agoNot to be grating but your problem sounds more like using the wrong tool for the job. DOM is not made to render video game UI, it is a bad tool to do so as you discovered yourself.
- Sawamara 8y agoTell that to Guild Wars 2. (https://mithril.js.org/framework-comparison.html https://mithril.js.org/framework-comparison.html) But putting even those games aside which use webview for UI, there are still video games made inside the browser, and for those, having sub-1ms rerender times with React is perfectly reasonable. We could get into immediate mode vs retained mode debates right about here, but that is a slightly different topic :D
- deleted 8y ago[deleted]
- vfc1 8y agoAngular also works in a somewhat similar way, there is also no virtual DOM. Instead, the modern compiler is used at build time to generate what looks like a change detection function and a DOM update function per component. These functions will detect changes and update the DOM in an optimal way without any DOM diffing. However, because Javascript objects by default are mutable, after each browser event Angular in its default change detection mode has to check all the template expressions in all the components for changes, because the browser event might have potentially triggered changes in any part of the component tree. If we want to introduce some restrictions and make the data immutable, then we can check only the components that received new data by using OnPush change detection, and even bypass whole branches of the component tree. This is the current state of things, for the near future Angular is having it's internals rebuilt in a project called Ivy. One of the main goals of Icy is to implement a principle called component locality. Ivy aims at getting to a point where if we change only one component, we only have to recompile that component and not the whole application. I think the article puts the focus on the wrong thing. The current change detection and DOM update mechanisms made available by modern frameworks virtual DOM or not are more than fast enough for users to notice, including on mobile and once the application is started. What we need is ways to ship less code to the browser, because that extra payload makes a huge difference in application startup time.
- 2T1Qka0rEiPr 8y agoThanks for the write up - it's a very succinct explanation of how Angular works in comparison. I found the original article to be a really good read, and the Svelte approach in general seems rather neat. I do however find that in this current front-end framework sphere, there seems to be a huge amount of religiosity and one-upping going on. I hear routinely (on-line and off) developers vocalising some anti-[jQuery,angular,etc.] mantra, which to be honest saddens me. Yes the jQuery approach was flawed in so many ways in comparison to the modern frameworks. Yes Angular 1.x was flawed in many ways compared to what we have on offer today. But those tools were still great improvements on what we had before (for anyone who knew the DOM-API standardisation nightmares pre-jQuery, or state management / testability woes pre angular/react). Svelte may take us down the next path, and if it allows us to produce better, smaller, more testable code then it has my full backing. But I think as a community we need to strive to be less polarising - from my perspective its likely to be mostly reductive, and lead to even more JavaScript fatigue.
- beders 8y agoIt is simply mind-boggling how much effort the JS community has put into working around the performance properties of a document layout engine to make it 'interactive' and 'responsive'. With only 3 major rendering engines left standing, where is the concerted push to turn these document renders into general purpose, fast, desktop-quality rendering engines? Back to Svelte vs. React vs. Reagent vs. Vue.JS vs. Angular vs. (insert framework-of-the-month-here) One common theme seems to be: Run code to manipulate a tree-like data structure (DOM) efficiently. This obviously needs to become: Submit data to the rendering engine to manipulate the tree-like structure. (and in a way .innerHtml is doing that for a sub-tree, but is not suitable for general-purpose tree manipulation)
- writepub 8y ago> where is the concerted push to turn these document renders into general purpose, fast, desktop-quality rendering engines The DOM is fast enough for desktop apps @60 or even 90 frames per second, especially of you follow best practices (no framework required)
- beders 8y agoIf it is fast enough, why is everyone optimizing?
- writepub 8y agoI hope you read the original article, that clearly lays out the (non) optimizations being done in VDOM. In any compute environment, doing more than necessary spins CPU cycles wastefully. I believe the optimizations you speak of try to limit this work to the least possible, by telling on the framework's Dev world. But this is surprisingly easy to achieve without frameworks, see [1] and [2] [1]: https://github.com/wilsonpage/fastdom https://github.com/wilsonpage/fastdom [2]: https://youtu.be/sFMpS2_GqQc https://youtu.be/sFMpS2_GqQc
- robocat 8y agoFor an individual developer it is not obvious how you should structure your usage of the DOM API to avoid the performance potholes and other problems. Even a team of experts in the DOM will sometimes take shortcuts or one expert's technique doesn't play nicely with another's. Some parts of the DOM are extremely slow if the API is used naturally, and obvious usage of the API has other side-effect penalties (e.g. stored state, difficult component destruction, or reference loops causing memory blowouts). So the vast majority of developers use the native DOM in such a way that the page is slow and buggy. React et al provide a clean API that avoids the worst performance problems, while providing a framework that steers a team towards good practices, so the average developer can be productive. The framework has a bunch of extra overhead, but the overhead is far less than the average overhead of not using the framework.
- fpoling 8y agoDirect manipulations of DOM are expensive. It is vastly more cheaper to create or update JS object than create or manipulate DOM node. So the claim that VirtualDom is always an overhead is not true. The diff algorithm can give a set of DOM operations that are less expensive than typical sequence of manual mutations. So virtual DOM can be faster if savings from less DOM operations are bigger than extra JS work. Surely carefully crafted direct DOM mutations will be the fastest approach, but it typically leads to hard to maintain code.
- kanonk 8y agoSeems like the author - and a lot of people here - have failed to realize this. This is the real benefit in DOM manipulations with VDOM.
- nsonha 8y agothe author and others did not avocate manual DOM manipulations. He wrote a framework that can generate optimal DOM manipulation code without the need of a virtual DOM.
- atan 8y agoI'm not sure you understood the article. The Svelte compiler does in fact generate code that performs "carefully crafted direct DOM mutations," though it is not hard to maintain, because the compiler handles it. Given code that already knows exactly which DOM updates to make, virtual DOM would indeed be pure overhead.
- fpoling 7y agoTypical React code does not know which updates to make. It always builds the Virtual DOM from scratch as is was the first time. It is the diff algorithm then figures out the set of changes. If code knows which updates to make, it essentially embeds a particular form of the diff algorithm. That inevitably leads to more code to write as besides the initial construction of DOM one has to track changes. And such manual tracking is not necessary optimal as the diff algorithm has a global picture and can target the globally optimally set of mutations, while manual in-component tracking optimizes for a particular component.
- _pdp_ 8y agoWriting some basic apps with vanila js is fine. But I think we use browsers for much more than this these days. For that we do need this level of overhead because DOM is just too simple for the task.
- DigitalSea 8y agoThis is why I use Aurelia. It's a Javascript framework many here have probably never heard of or used, it debuted in 2015 and I have been working with it for four years now. Sadly Aurelia debuted at the height of the React hype and soon after, Vue hype. Rob Eisenberg (the man in charge of the Aurelia project) had the right idea straight out of the gate. A reactive binding and observation system that worked like a virtual DOM (isolated specific non-destructive DOM operations) without the need for an actual virtual DOM. Which allows you to use any third-party library without worrying about compatibility or timing issues with the UI. This is one area where React falters, at least when I used it. third party libraries clashed with the virtual DOM. When you start introducing abstractions to solve imaginary problems caused by improperly written code (the myth of the DOM being slow) you introduce issues you have to battle later on as your application scales.
- Tobani 8y agoThe default behavior for javascript interacting with the DOM is incredibly slow once the page gets complicated enough. I've certainly seen it first-hand. This may not be a problem you have, and indeed maybe not everybody needs react. But the problems things like react/vue/whatever solve (correctly or not) isn't imaginary.
- baybal2 8y agoThis is what I use when I need to do very minimalistic UI and feel that bringing Vue/React is an overkill https://github.com/adamhaile/S https://github.com/adamhaile/S - reactivity without DOM superglue to it.
- amelius 8y agoI think most people in this thread focus too much on the vdom, and miss the important part of the post: > Unlike traditional UI frameworks, Svelte is a compiler that knows at build time how things could change in your app, rather than waiting to do the work at run time.
- keepsmiling 8y agohello very great article. i've been working as a developer for over 20 years now and have to say that do more experience you have on fewer and fewer trains you jump on what should not be heisen that i don't look at frameworks anymore but to describe it it's just often too much of a good thing. every framework has good pages but you should keep it simple. ciao
- patsplat 7y agoDouble buffering is a standard rendering technique. It might be pure overhead but it won't look that way.
- peterbraden 7y agoIt's not double buffering - double buffering is just calculation into memory and then a memory update. VDOM is essentially calculating the buffer once in a scripting language, and then again in a fast way if necessary. Despite that, it may still be a good idea.
- gr__or 7y agoI wrote about this a while ago, and now I wonder whether I read this post at some point in the past. Anyway, here it is: https://dflate.io/svelte-react-reconciliation https://dflate.io/svelte-react-reconciliation
- shmooth 7y agowho actually created the concept of the virtual DOM?
- snewcomer24 7y agoHere are some measurements of vdom vs plain ol DOM manipulation - https://github.com/patrick-steele-idem/morphdom#benchmarks https://github.com/patrick-steele-idem/morphdom#benchmarks