alexmaday
10/11/2017 - 8:18 PM

The operation consists to append 12 nodes to an existing parent node with 1000 children Three ways to do it: 1. Use parentNode.innerHTML

The operation consists to append 12 nodes to an existing parent node with 1000 children

Three ways to do it:

  1. Use parentNode.innerHTML +=

  2. User parentNode.innerHTML =

  3. Use a parentNode.appendChild inside a loop.

The method with the best performance is the last one. The last method doesn't need to read the current DOM or parse it.

var mainNodeInner = document.createElement('div'),
            mainNodeInnerPlus = document.createElement('div'),
            mainNodeAppend = document.createElement('div'),
            sampleHTML = '<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>',
            testHTML = '',
            numSamples = 1000,
            before = null,
            after = null;

        //SET UP
        for (i = 0; i < numSamples; i++) {
            testHTML += sampleHTML;
        }


        //INNER HTML +=
        mainNodeInnerPlus.innerHTML = testHTML;

        before = new Date().getTime();
        mainNodeInnerPlus.innerHTML += sampleHTML;
        after = new Date().getTime();

        console.log("TIME INNER HTML +=: " + (after - before) + " ms");
        console.log("Num childs after: " + mainNodeInnerPlus.childElementCount);

        console.log(' ');

        //INNER HTML =
        var allHTML = testHTML + sampleHTML;

        before = new Date().getTime();
        mainNodeInner.innerHTML = allHTML;
        after = new Date().getTime();

        console.log("TIME INNER HTML =: " + (after - before) + " ms");
        console.log("Num childs after: " + mainNodeInner.childElementCount);

        console.log(' ');

        //APPEND CHILD
        mainNodeAppend.innerHTML = testHTML;

        before = new Date().getTime();
        var sampleNode = document.createElement('div');
        sampleNode.innerHTML = sampleHTML;

        while(sampleNode.hasChildNodes()) {
            mainNodeAppend.appendChild(sampleNode.firstChild);
        }
        after = new Date().getTime();
        console.log("TIME APPEND CHILD: " + (after - before) + " ms");
        console.log("Num childs after: " + mainNodeAppend.childElementCount);