JSFiddle - React, Tailwind, and code Playground

by chrisbenseler

HTML

<html>
    <head>
        <title>Perfomance criação de elementos</title>            
    </head>
    <body>
    <a href="#" id="sem_fragment">criar sem documentFragment</a>
    <a href="#" id="com_fragment">criar com documentFragment</a>
    <div id="container">
       
    </div>
    </body>
</html>

JavaScript

var Profiler = function() {
    var start_date = null;
    var stop_date = null;
    this.start = function() {
        start_date = (new Date()).getTime();
    }

    this.stop = function() {
        stop_date = (new Date()).getTime();
    }

    this.delay = function() {
        return stop_date - start_date;
    }
}

function remove_all_nodes(el) {
    if (el.hasChildNodes())    {
        while(el.childNodes.length >= 1) {
            el.removeChild(el.firstChild);
        }
    }
}

window.onload = function() {
    var div = document.getElementById("container");
    var prof = new Profiler();
    var total_items = 50000;
    document.getElementById("sem_fragment").onclick = function() {
        remove_all_nodes(div);
        prof.start();
        for(var i=0; i<total_items; i++) {
            var d = document.createElement("p");
            div.appendChild(d);
        }
        prof.stop();
        
        alert(prof.delay() + " milisegundos para criar " +  total_items + " elementos <p>");
    }


    document.getElementById("com_fragment").onclick = function() {
        remove_all_nodes(div);
        prof.start();
        var fragment = document.createDocumentFragment();
        for(var i=0; i<total_items; i++) {
            var d = document.createElement("p");
            fragment.appendChild(d);
        }
        div.appendChild(fragment);
        prof.stop();
        
        alert(prof.delay() + " milisegundos para criar " +  total_items + " elementos <p>");
    }
}