> From: Martin Tiršel
> I need to hold some things in memory for later use, so pure 
> html is not ideal. I will try JSON, if it will be under 5-7 
> seconds for 500 items, it should be ok.

In fact, you can get it much faster than that, even in IE.

Let's assume your JSON data is an exact mirror of the XML:

    {
        "pages": [
            {
                "name": "the name",
                "id": 5,
                "url": "http://example.com/";,
                "author": {
                    "id": 7,
                    "name": "the author"
                },
                "languages": [
                    "sk",
                    "cz"
                ]
            },
            {
                // another page
            },
            {
                // ...
            }
        ]
    }

and assume you have a reference to this data in a variable called "json".

You can write:

    $("#content_window_pages").append( makeTable(json.pages) );

    function makeTable( pages ) {
        var html = [], h = -1;
        html[++h] = '<table class="pagelist">';
        html[++h] = '<thead><tr>';
        html[++h] =     '<th>Name</th>';
        html[++h] =     '<th>Author</th>';
        html[++h] =     '<th>Languages</th>';
        html[++h] =     '<th>Actions</th>';
        html[++h] = '</tr></thead>';
        html[++h] = '<tbody>';
        for( var page, i = -1;  page = pages[++i]; ) {
            html[++h] = '<tr><td class="first">';
            html[++h] =     page.name;
            html[++h] = '</td><td class="second">';
            html[++h] =     page.author.name;
            html[++h] = '</td><td class="third">';
            html[++h] =     page.languages.join();
            html[++h] = '</td><td class="fourth">&nbsp;</td></tr>';
        }
        html[++h] = '</tbody>';
        html[++h] = '</table>';
        return html.join('');
    }

I think you will be very pleased with the speed of this code. And it's much
simpler than the XML version too. The html[++h] = business is a bit ugly,
but it's by far the fastest way to build up a long string in IE, and since
IE is both the most widespread browser and the slowest at this, it's the one
you need to worry about.

I broke up the <thead> section into multiple html[++h] = assignments just to
keep the line length short in this message, but you could combine those into
one as in your original code if you prefer. It's not performance critical so
it's just a matter of taste. For the code *inside* the inner loop I combined
assignments as much as possible, as in the last line of the inner loop.
 
-Mike

Reply via email to