Why is React’s concept of Virtual DOM said to be more performant than dirty model checking?

Questions : Why is React’s concept of Virtual DOM said to be more performant than dirty model checking?

I saw a React dev talk at (Pete Hunt: React: Rethinking best practices — JSConf EU 2013) and the speaker mentioned that dirty-checking of the model can be slow. But isn’t calculating the diff between virtual DOMs actually even less performant since the virtual DOM, in most of the cases, should be bigger than model?

I really like the potential power of the Virtual DOM (especially server-side rendering) but I would like to know all the pros and cons.

Total Answers: 6 Answers 6


Popular Answers:

  1. I really like the potential power of the Virtual DOM (especially server-side rendering) but I would like to know all the pros and cons.

    — OP

    React is not the only DOM manipulation library. I encourage you to understand the alternatives by reading this article from Auth0 that includes detailed explanation and benchmarks. I’ll highlight here their pros and cons, as you asked:

    React.js’ Virtual DOM

    enter image description here

    PROS

    • Fast and efficient “diffing” algorithm
    • Multiple frontends (JSX, hyperscript)
    • Lightweight enough to run on mobile devices
    • Lots of traction and mindshare
    • Can be used without React (i.e. as an independent engine)

    CONS

    • Full in-memory copy of the DOM (higher memory use)
    • No differentiation between static and dynamic elements

    Ember.js’ Glimmer

    enter image description here

    PROS

    • Fast and efficient diffing algorithm
    • Differentiation between static and dynamic elements
    • 100% compatible with Ember’s API (you get the benefits without major updates to your existing code)
    • Lightweight in-memory representation of the DOM

    CONS

    • Meant to be used only in Ember
    • Only one frontend available

    Incremental DOM

    enter image description here

    PROS

    • Reduced memory usage
    • Simple API
    • Easily integrates with many frontends and frameworks (meant as a template engine backend from the beginning)

    CONS

    • Not as fast as other libraries (this is arguable, see the benchmarks below)
    • Less mindshare and community use
  2. In React, each of your components have a state. This state is like an observable you might find in knockout or other MVVM style libraries. Essentially, React knows when to re-render the scene because it is able to observe when this data changes. Dirty checking is slower than observables because you must poll the data at a regular interval and check all of the values in the data structure recursively. By comparison, setting a value on the state will signal to a listener that some state has changed, so React can simply listen for change events on the state and queue up re-rendering.The virtual DOM is used for efficient re-rendering of the DOM. This isn’t really related to dirty checking your data. You could re-render using a virtual DOM with or without dirty checking. You’re right in that there is some overhead in computing the diff between two virtual trees, but the virtual DOM diff is about understanding what needs updating in the DOM and not whether or not your data has changed. In fact, the diff algorithm is a dirty checker itself but it is used to see if the DOM is dirty instead.

    We aim to re-render the virtual tree only when the state changes. So using an observable to check if the state has changed is an efficient way to prevent unnecessary re-renders, which would cause lots of unnecessary tree diffs. If nothing has changed, we do nothing.

  3. Virtual Dom is not invented by react. It is part of HTML dom. It is lightweight and detached from the browser-specific implementation details.

    We can think virtual DOM as React’s local and simplified copy of the HTML DOM. It allows React to do its computations within this abstract world and skip the “real” DOM operations, often slow and browser-specific. Actually there is no big differenc between DOM and VIRTUAL DOM.

    Below are the points why Virtual Dom is used (source Virtual DOM in ReactJS):

    When you do:

    document.getElementById('elementId').innerHTML = "New Value" Following thing happens: 
    1. Browser needs to parse the HTML
    2. It removes the child element of elementId
    3. Updates the DOM value with new value
    4. Re-calculate the css for the parent and child
    5. Update the layout i.e. each elements exact co-ordinates on the screen
    6. Traverse the render tree and paint it on the browser display

    Recalculating the CSS and changed layouts uses complex algorithm and they effect the performance.

    As well as updating the DOM properties ie. values. It follows a algorithm.

    Now, suppose if you update DOM 10 times directly, then all the above steps will run one by one and updating DOM algorithms will take time to updates DOM values.

    This, is why Real DOM is slower than virtual DOM.

  4. Most professional programmers suck

    I have come across too many people doing this job for their living who were plain crappy at what they were doing. Crappy code, bad communication skills, no interest in new technology whatsoever. Too many, too many…

  5. A degree in computer science does not—and is not supposed to—teach you to be a programmer.

    Programming is a trade, computer science is a field of study. You can be a great programmer and a poor computer scientist and a great computer scientist and an awful programmer. It is important to understand the difference.

    If you want to be a programmer, learn Java. If you want to be a computer scientist, learn at least three almost completely different languages. e.g. (assembler, c, lisp, ruby, smalltalk)

  6. SESE (Single Entry Single Exit) is not law

    Example:

    public int foo() { if( someCondition ) { return 0; } return -1; } 

    vs:

    public int foo() { int returnValue = -1; if( someCondition ) { returnValue = 0; } return returnValue; } 

    My team and I have found that abiding by this all the time is actually counter-productive in many cases.

  7. C++ is one of the WORST programming languages – EVER.

    It has all of the hallmarks of something designed by committee – it does not do any given job well, and does some jobs (like OO) terribly. It has a “kitchen sink” desperation to it that just won’t go away.

    It is a horrible “first language” to learn to program with. You get no elegance, no assistance (from the language). Instead you have bear traps and mine fields (memory management, templates, etc.).

    It is not a good language to try to learn OO concepts. It behaves as “C with a class wrapper” instead of a proper OO language.

    I could go on, but will leave it at that for now. I have never liked programming in C++, and although I “cut my teeth” on FORTRAN, I totally loved programming in C. I still think C was one of the great “classic” languages. Something that C++ is certainly NOT, in my opinion.

    Cheers,

    -R

    EDIT: To respond to the comments on teaching C++. You can teach C++ in two ways – either teaching it as C “on steroids” (start with variables, conditions, loops, etc), or teaching it as a pure “OO” language (start with classes, methods, etc). You can find teaching texts that use one or other of these approaches. I prefer the latter approach (OO first) as it does emphasize the capabilities of C++ as an OO language (which was the original design emphasis of C++). If you want to teach C++ “as C”, then I think you should teach C, not C++.

    But the problem with C++ as a first language in my experience is that the language is simply too BIG to teach in one semester, plus most “intro” texts try and cover everything. It is simply not possible to cover all the topics in a “first language” course. You have to at least split it into 2 semesters, and then it’s no longer “first language”, IMO.

    I do teach C++, but only as a “new language” – that is, you must be proficient in some prior “pure” language (not scripting or macros) before you can enroll in the course. C++ is a very fine “second language” to learn, IMO.

    -R

    ‘Nother Edit: (to Konrad)

    I do not at all agree that C++ “is superior in every way” to C. I spent years coding C programs for microcontrollers and other embedded applications. The C compilers for these devices are highly optimized, often producing code as good as hand-coded assembler. When you move to C++, you gain a tremendous overhead imposed by the compiler in order to manage language features you may not use. In embedded applications, you gain little by adding classes and such, IMO. What you need is tight, clean code. You can write it in C++, but then you’re really just writing C, and the C compilers are more optimized in these applications.

    I wrote a MIDI engine, first in C, later in C++ (at the vendor’s request) for an embedded controller (sound card). In the end, to meet the performance requirements (MIDI timings, etc) we had to revert to pure C for all of the core code. We were able to use C++ for the high-level code, and having classes was very sweet – but we needed C to get the performance at the lower level. The C code was an order of magnitude faster than the C++ code, but hand coded assembler was only slightly faster than the compiled C code. This was back in the early 1990s, just to place the events properly.

    -R

  8. A degree in Computer Science or other IT area DOES make you a more well rounded programmer

    I don’t care how many years of experience you have, how many blogs you’ve read, how many open source projects you’re involved in. A qualification (I’d recommend longer than 3 years) exposes you to a different way of thinking and gives you a great foundation.

    Just because you’ve written some better code than a guy with a BSc in Computer Science, does not mean you are better than him. What you have he can pick up in an instant which is not the case the other way around.

    Having a qualification shows your commitment, the fact that you would go above and beyond experience to make you a better developer. Developers which are good at what they do AND have a qualification can be very intimidating.

    I would not be surprized if this answer gets voted down.

    Also, once you have a qualification, you slowly stop comparing yourself to those with qualifications (my experience). You realize that it all doesn’t matter at the end, as long as you can work well together.

    Always act mercifully towards other developers, irrespective of qualifications.

  9. Lazy Programmers are the Best Programmers

    A lazy programmer most often finds ways to decrease the amount of time spent writing code (especially a lot of similar or repeating code). This often translates into tools and workflows that other developers in the company/team can benefit from.

    As the developer encounters similar projects he may create tools to bootstrap the development process (e.g. creating a DRM layer that works with the company’s database design paradigms).

    Furthermore, developers such as these often use some form of code generation. This means all bugs of the same type (for example, the code generator did not check for null parameters on all methods) can often be fixed by fixing the generator and not the 50+ instances of that bug.

    A lazy programmer may take a few more hours to get the first product out the door, but will save you months down the line.

  10. Don’t use inheritance unless you can explain why you need it.

  11. The world needs more GOTOs

    GOTOs are avoided religiously often with no reasoning beyond “my professor told me GOTOs are bad.” They have a purpose and would greatly simplify production code in many places.

    That said, they aren’t really necessary in 99% of the code you’ll ever write.

  12. I’ve been burned for broadcasting these opinions in public before, but here goes:

    Well-written code in dynamically typed languages follows static-typing conventions

    Having used Python, PHP, Perl, and a few other dynamically typed languages, I find that well-written code in these languages follows static typing conventions, for example:

    • Its considered bad style to re-use a variable with different types (for example, its bad style to take a list variable and assign an int, then assign the variable a bool in the same method). Well-written code in dynamically typed languages doesn’t mix types.

    • A type-error in a statically typed language is still a type-error in a dynamically typed language.

    • Functions are generally designed to operate on a single datatype at a time, so that a function which accepts a parameter of type T can only sensibly be used with objects of type T or subclasses of T.

    • Functions designed to operator on many different datatypes are written in a way that constrains parameters to a well-defined interface. In general terms, if two objects of types A and B perform a similar function, but aren’t subclasses of one another, then they almost certainly implement the same interface.

    While dynamically typed languages certainly provide more than one way to crack a nut, most well-written, idiomatic code in these languages pays close attention to types just as rigorously as code written in statically typed languages.

    Dynamic typing does not reduce the amount of code programmers need to write

    When I point out how peculiar it is that so many static-typing conventions cross over into dynamic typing world, I usually add “so why use dynamically typed languages to begin with?”. The immediate response is something along the lines of being able to write more terse, expressive code, because dynamic typing allows programmers to omit type annotations and explicitly defined interfaces. However, I think the most popular statically typed languages, such as C#, Java, and Delphi, are bulky by design, not as a result of their type systems.

    I like to use languages with a real type system like OCaml, which is not only statically typed, but its type inference and structural typing allow programmers to omit most type annotations and interface definitions.

    The existence of the ML family of languages demostrates that we can enjoy the benefits of static typing with all the brevity of writing in a dynamically typed language. I actually use OCaml’s REPL for ad hoc, throwaway scripts in exactly the same way everyone else uses Perl or Python as a scripting language.

  13. Programmers who spend all day answering questions on Stackoverflow are probably not doing the work they are being paid to do.

  14. Code layout does matter

    Maybe specifics of brace position should remain purely religious arguments – but it doesn’t mean that all layout styles are equal, or that there are no objective factors at all!

    The trouble is that the uber-rule for layout, namely: “be consistent”, sound as it is, is used as a crutch by many to never try to see if their default style can be improved on – and that, furthermore, it doesn’t even matter.

    A few years ago I was studying Speed Reading techniques, and some of the things I learned about how the eye takes in information in “fixations”, can most optimally scan pages, and the role of subconsciously picking up context, got me thinking about how this applied to code – and writing code with it in mind especially.

    It led me to a style that tended to be columnar in nature, with identifiers logically grouped and aligned where possible (in particular I became strict about having each method argument on its own line). However, rather than long columns of unchanging structure it’s actually beneficial to vary the structure in blocks so that you end up with rectangular islands that the eye can take in in a single fixture – even if you don’t consciously read every character.

    The net result is that, once you get used to it (which typically takes 1-3 days) it becomes pleasing to the eye, easier and faster to comprehend, and is less taxing on the eyes and brain because it’s laid out in a way that makes it easier to take in.

    Almost without exception, everyone I have asked to try this style (including myself) initially said, “ugh I hate it!”, but after a day or two said, “I love it – I’m finding it hard not to go back and rewrite all my old stuff this way!”.

    I’ve been hoping to find the time to do more controlled experiments to collect together enough evidence to write a paper on, but as ever have been too busy with other things. However this seemed like a good opportunity to mention it to people interested in controversial techniques 🙂

    [Edit]

    I finally got around to blogging about this (after many years parked in the “meaning to” phase): Part one, Part two, Part three.

  15. Opinion: explicit variable declaration is a great thing.

    I’ll never understand the “wisdom” of letting the developer waste costly time tracking down runtime errors caused by variable name typos instead of simply letting the compiler/interpreter catch them.

    Nobody’s ever given me an explanation better than “well it saves time since I don’t have to write ‘int i;’.” Uhhhhh… yeah, sure, but how much time does it take to track down a runtime error?

  16. Opinion: Never ever have different code between “debug” and “release” builds

    The main reason being that release code almost never gets tested. Better to have the same code running in test as it is in the wild.

  17. Pagination is never what the user wants

    If you start having the discussion about where to do pagination, in the database, in the business logic, on the client, etc. then you are asking the wrong question. If your app is giving back more data than the user needs, figure out a way for the user to narrow down what they need based on real criteria, not arbitrary sized chunks. And if the user really does want all those results, then give them all the results. Who are you helping by giving back 20 at a time? The server? Is that more important than your user?

    [EDIT: clarification, based on comments]

    As a real world example, let’s look at this Stack Overflow question. Let’s say I have a controversial programming opinion. Before I post, I’d like to see if there is already an answer that addresses the same opinion, so I can upvote it. The only option I have is to click through every page of answers.

    I would prefer one of these options:

    1. Allow me to search through the answers (a way for me to narrow down what I need based on real criteria).

    2. Allow me to see all the answers so I can use my browser’s “find” option (give me all the results).

    The same applies if I just want to find an answer I previously read, but can’t find anymore. I don’t know when it was posted or how many votes it has, so the sorting options don’t help. And even if I did, I still have to play a guessing game to find the right page of results. The fact that the answers are paginated and I can directly click into one of a dozen pages is no help at all.


    bmb

  18. Respect the Single Responsibility Principle

    At first glance you might not think this would be controversial, but in my experience when I mention to another developer that they shouldn’t be doing everything in the page load method they often push back … so for the children please quit building the “do everything” method we see all to often.

Tasg: javascript, dom

Answer Link
jidam
  • Unable to run NoraUI mvn verify goal
  • Unable to run my app on emulator in VS Code
  • Unable to run multiple instances of libVLC(MobileVLCKit) in IOS via flutter framework
  • Unable to run make on griddb source on ubuntu 20.04 (building from source)
  • Unable to run latexindent macOS Monterey 12.0.1
  • Unable to run kotlinc-native command
  • Unable to run JUnit Test… Java.lang.ExceptionInInitializerError (Android Studio)
  • Unable to run java with -Xmx > 966m
  • Unable to run ionic cap run android from wsl2 inorder to start android emulator
  • Unable to run Intel HAXM installer: Cannot start process, the working directory does not exist
  • fs
  • Unable to run Google Analytics sample code
  • unable to run flutter run after upgarding to flutter 2.8.0 from 2.5.3
  • Unable to run Django with PostgreSQL in Docker
  • Unable to Run Container Using testcontainers
  • Unable to run ClojureScript Hello World program, Error building classpath. Error reading edn.
  • unable to run client command for apache karaf 4.3.3 through remote server
  • Unable to run c program 2nd time using eclipse
  • unable to run c++ in visual studio code on m1 chipset
  • Unable to run Android Instrumented Tests
  • Unable to run adb, check your Android SDK installation and ANDROID_SDK_ROOT environment variable: …AndroidSdkplatform-toolsadb.exe
  • Unable to run a singlespecific .spec.ts file through angular cli using ng test –include option
  • Unable to run a Mango query
  • Unable to return response back to view in laravel from package
  • Unable to return object reference in std::optional
  • Unable to return NULL in a function that expects an integer return type
  • Unable to return correct change in JavaScript Cash Register
  • Unable to retrieve version information from Elasticsearch nodes. Request timed out
  • Unable to retrieve values from Axios Response data
  • Unable to retrieve dotenv JWT secret Error: secretOrPrivateKey must have a value
  • Unable to resolve your shell environment
  • Unable to resolve token for FCM while implementing Push notification for Xamarin
  • Unable to resolve the request yii
  • Unable to resolve service for type Swashbuckle.AspNetCore.Swagger.ISwaggerProvider
  • Unable to resolve service for type Microsoft.EntityFrameworkCore.Diagnostics.IDiagnosticsLogger