Search code examples
javascriptperformancereactjsvirtual-dom

How virtual DOM increases speed for ReactJS?


I read that ReactJS is very fast compared to other frameworks because if uses virtual dom.

What I am not able to understand is ultimately all framework has to push dom objects in browser. How virtualDom helps gaining speed?

Lets say if I want to add 10K node list, shouldn't required DOM operation time be similar for ReactJS and other frameworks?


Solution

  • First you have to keep in mind that DOM operations (repaints, reflows) are a lot more expensive than Javascript operations.

    For example (contrived), updating a

    • live DOM element might cost 3 seconds
    • virtual DOM element might take 1 second

    Now let's say i have a DOM

    <ul>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
    </ul>
    

    And lets say you want to update it to

    <ul>
        <li>First Item</li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
    </ul>
    

    Without virtual dom it would repaint all 6 elements on the screen which would take 3x6=18 seconds

    Using a virtual dom we can paint it in memory and it would cost us 6 seconds. After we've painted, we can compare what has changed, in our case 1 element - we can paint this element in 3 seconds so we've done this operation in 9 seconds (which is faster than without the virtual dom).

    Of course, you can imagine that not all cases will benefit from the virtual dom but in most cases using the virtual dom is a significant improvement.

    The key assumption is that live DOM repaints/reflows are a lot more expensive than a virtual DOM.