1000 times more performance optimization when calling innerHTML property in a loop

innerHTML is an API for JavaScript to access dom. Since the two independent functions of js and dom are connected to each other through the interface, consumption will occur.
So accessing the dom element is expensive, and modifying the element is more expensive, because it causes the browser to recalculate the geometric changes of the page.
The worst case is accessing or modifying elements in a loop, especially looping over a collection of HTML elements.
This is the difference between the following two writing cycles of 15,000 times on Google Chrome. You read that right. The difference between the two writing methods can reach more than 1,000 times.
write picture description here

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="here">1</div>
        <script>
            function innerHTMLLoop(){
                console.time();
                for(var count = 0; count <15000; count++){
                    document.getElementById('here').innerHTML += 'a';
                }
                console.timeEnd();
            }
            innerHTMLLoop();
            function innerHTMLLoop1(){
                console.time();
                var content = '';
                for(var count = 0; count <15000; count++){
                    content += 'a';
                }
                document.getElementById('here').innerHTML += content;
                console.timeEnd();
            }
            innerHTMLLoop1()
        </script>
    </body>
</html>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325648619&siteId=291194637