views:

610

answers:

3

I was testing something I read earlier about how random Math.random() really is, and wanted to display 10000 numbers that was supposed to be a random number between 0 and 10000000.

To see the test, I chose to just join the array of random numbers to a string with <br> between each integer. And then I just did $("#"+elm).html(randomNumberString); which was really slow. I just figured it was the generation and sorting of random numbers into an array. But as I started placing timers in my code, it got appearant that it was the output that was slowing everything down.

Just as a test I did document.getElementById(elm).innerHTML = randomNumberString;

jQuery.html(): 2500ms getElementById.innerHTML: 170ms

I tried this across all 5 browsers, and the numbers were very close in all browsers... Am I using jQuery wrong in this instance? I also tried append and fetching the element before the timer started, so I could simply do $(elm).html(), but that didn't help. It seems to be the actual html() function that's slowing everything down..?

EDIT I ended up doing this:

randomStringNumber = "<div>" + randomStringNumber + "</div>";

and now the whole thing runs a lot faster: jQuery.html(): 120ms getElementById.innerHTML: 80ms

Still faster using oldschool html, though. And if anyone has an answer to why wrapping it in one element is faster, I'd appreciate that...

+3  A: 

25 tip to improve your jquery use

http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx

Haim Evgi
Point 7 seems to be the relevant one
Greg
nice! No idea why it's faster, though... hmmmmm.....
peirix
+1  A: 

This seems like a limitation of the html function. In this discussion the following function was suggested as replacement:

$.fn.replaceHtml = function( val ) {
    var stack = [];
    return this.each( function(i, el) {
        var oldEl = el;
        /*@cc_on // Pure innerHTML is slightly faster in IE
        oldEl.innerHTML = html;
        return oldEl;
        @*/
        var newEl = oldEl.cloneNode(false);
        newEl.innerHTML = html;
        oldEl.parentNode.replaceChild(newEl, oldEl);
        /* Since we just removed the old element from the DOM, return a reference
        to the new element, which can be used to restore variable references. */
        stack.push( newEl );
    }).pushStack( stack );
};
Darin Dimitrov
A: 

The fastest way is this:

 $.getJSON("/Admin/GetFolderList/", function(result) {
        var optionsValues = '<select>';
        $.each(result, function(item) {
      optionsValues += '<option value="' + item.ImageFolderID + '">' + item.Name + '</option>';
        });
     optionsValues += '</select>';
     var options = $('#options');
     options.replaceWith(optionsValues);
    });

According to this link is the fastest way because you wrap everything in a single element when doing any kind of DOM insertion.

Ricibald