Anton
Anton

Reputation: 11360

Best way to construct big html table

Scenario I'd like to construct table from pieces: header, each row in from items array, end. And then add it to page.

Code

Initially, I've tried to immediately add each piece via $("#output").append(piece), but browser automatically closes open tags.

So, currently, I concatenate string first and then set html. As I understood, the best way to concatenate big amount of strings is to accumulate them in array and then join, as fastest way to set html is to use innerHTML DOM property:

// Big array of data objects
var items = [...]; // Big amount of items

// Class, which constructs HTML
var drawer = new UiDrawer();

// Generate
var result = [];

result.push( drawer.getHeader() ); // <table>

items.forEach(function (item) {
    result.push( drawer.getItem(item) ); // <tr> <td>item N</td> </tr>
});

result.push( drawer.getFooter() );

// Add to page
$("#output")[0].innerHTML = result.join(""); // </table>

Is this a right way to do that? Can I construct html sequentially, without keeping it first in array?


Testing things

So, currently three ways of doing this were mentioned:

I've created small page to test performance of all these methods: enter image description here

So, array concatenation is, probably, the fastest way.

Here simple code, which was used to test those approaches:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.1/css/jquery.dataTables.css">       
        <script type="text/javascript" charset="utf8" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>       
        <script type="text/javascript" charset="utf8" src="http://cdn.datatables.net/1.10.1/js/jquery.dataTables.js"></script>
    </head>
    <body>
        <div id="meta"></div>
        <div id="output"></div>
        <script>
            var meta = document.getElementById("meta");
            var output = document.getElementById("output");
            var rowsNumber = 10000;

            var items = [];
            for (var i = 0; i < rowsNumber; i++) {
                items.push(["#" + i, "Simple item"]);
            }           

            // Evaluates given function
            var evaluateWay = function(name, func) {
                var start = new Date();

                for (var i = 0; i < 10; i++) {
                    func();
                    output.innerHTML = "";
                }

                var finish = new Date();

                meta.innerHTML += "Ten iterations to draw table with " + items.length + " rows via '" + name + "' way took " + (finish - start) + " ms<br />";
                output.innerHTML = "";
            };

            // Array concatenation
            evaluateWay("Array concatenation", function () {
                var result = [];

                result.push( "<table>" );

                items.forEach(function (item) {
                    result.push( "<tr> <td>" + item[0] + "</td><td>" + item[1] + "</td> </tr>" );
                });

                result.push( "</table>" );

                // Add to page
                output.innerHTML = result.join(""); // </table>
            });

            // Document Fragments
            evaluateWay("Document Fragments", function () {
                var table = document.createElement('table');

                items.forEach(function (item) {
                    var row = document.createElement('tr');

                    var cell1 = document.createElement('td');
                    var cell2 = document.createElement('td');
                    cell1.innerHTML = item[0];
                    cell2.innerHTML = item[1];
                    row.appendChild(cell1);
                    row.appendChild(cell2);

                    table.appendChild(row);
                });

                output.appendChild(table);
            });

            // jQuery Table Plugin
            evaluateWay("jQuery Table Plugin", function () {
                output.innerHTML = '<table id="myTable"></table>';
                $('#myTable').dataTable( {
                    "data": items,
                    "columns": [
                        { },
                        { },
                    ]
                } ); 
            });
        </script>
    </body>
</html>

Upvotes: 0

Views: 3184

Answers (2)

Alessandro
Alessandro

Reputation: 1453

The fastest way I would say is native.

var items = ["a","b","c"];

var table = document.createElement('table');
var header = document.createElement('thead');
header.innerHTML = "<tr><td>Your Header</td></tr>";
var body = document.createElement('tbody');

items.forEach(function (item) {
    var row = document.createElement('tr');
    var cell = document.createElement('td');
    cell.innerHTML = item;
    row.appendChild(cell);
    body.appendChild(row);
});

table.appendChild(header);
table.appendChild(body);

document.getElementById('target').appendChild(table);

Edit

If you want a quick benchmark of your possibility to join elements from an array into a string you can run this script (maybe better put it inside a big foreach and take out some averages, I left this to you :) )

My results were that forEach is far slower than join but plain for is double fast than join

// Prepare array
var array = [];
for(var i=0;i<10000;i++) {
    array[i] = "a";    
}

var string = "";
var timestart = 0;
var timeend = 0;

// misure join time
timestart = window.performance.now();
string = array.join("");
timeend = window.performance.now();
joinTime = timeend-timestart;

// misure foreach time
string = "";
timestart = window.performance.now();
array.forEach(function (item) {
    string += item;
});
timeend = window.performance.now();
foreachTime = timeend-timestart;

// misure for time
string = "";
timestart = window.performance.now();
for (i=0; i<array.length; i++) {
    string += array[i];
}
timeend = window.performance.now();
forTime = timeend-timestart;

alert("Join time: " + joinTime + "\nForeach time: " + foreachTime + "\nFor time: " + forTime);

Upvotes: 2

Mazzu
Mazzu

Reputation: 2849

You can go for data table plugin, that work for more amount of data.

refer to link for more details http://www.datatables.net/

Upvotes: 0

Related Questions