Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Improve table rendering, fastest table render

So I have to render a table with 1000 rows and 1000 columns. Accordingly this link, it seems like the best way is to build the HTML string in javascript and then inserted it into the DOM all in one go. I made a simple example of this, and compare it with couple other methods. At the end, this is really the fastest way which I came out with. But still this is not satisfying enough. So my question is, is there a faster way, than the following example.

var startTime = new Date().getTime(),
    tableString = "<table>",
    body = document.getElementsByTagName('body')[0],
    div = document.createElement('div'),
    finalResult = 0,
    endTime = 0,
    result = 0;

for (row = 0; row < 1000; row += 1) {

    tableString += "<tr>";

    for (col = 0; col < 1000; col += 1) {

        tableString += "<td>" + "testing" + "</td>";
    }
    tableString += "</tr";
}

tableString += "</table>";
div.innerHTML = tableString;
body.appendChild(div);

endTime  = new Date().getTime();
console.log(endTime - startTime);
like image 586
sla55er Avatar asked Nov 16 '25 12:11

sla55er


1 Answers

A massive amount of string concatenation will get you into runtime trouble, no matter what language. The fastet way will be to go through the native JavaScript DOM API, while constructing your table within a document fragment. At the end of your function, insert that document fragment at the desired position in your document.

Something like this will create a table with 1000 rows and 20 cells per row:

function makeTable() {
    var fragment = document.createDocumentFragment();

    for (var i = 0; i < 1000; i++) {
        var row = document.createElement('tr');
        fragment.appendChild(row);

        for (var j = 0; j < 20; j++) {
            var cell = document.createElement('td');
            cell.appendChild(document.createTextNode(i.toString() + ', ' + j.toString()));
            row.appendChild(cell);
        }
    }

    var target = document.getElementById('target');
    target.appendChild(fragment);
}

JSFiddle: http://jsfiddle.net/KbNLb/4/

EDIT Just saw you did 1000x1000 - that is one million cells, that will be slow no matter what. I really hope on million table cells is not your actual use case. ;-)

like image 157
UweB Avatar answered Nov 18 '25 03:11

UweB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!