views:

50

answers:

4

Which code will work fastest?

for(i=0; i<100; i++) {
    jQuery("#myDiv").append("<span>" + i + "</span>");
}
//

var i, markup = "";
for (i=0; i<100; i++) {
    markup += "<span>" + i + "</span>";
}
//

jQuery("#myDiv").append(markup);

//
var i, markup = "";
for (i=0; i<100; i++) {
    markup += "<span>" + i + "</span>";
}

//
jQuery("#myDiv").append("<div>" + markup + "</div>");

//
A: 

It's difficult to tell, but here's a better one, works better on larger strings:

var markup = [];
for(int i=0;i<100;i++){
   markup.push('<span>' + i + '</span>');
}
jQuery('#myDiv').append(markup);
jerjer
+2  A: 

I would guess this one:

jQuery("#myDiv").append(markup);

I'd guess there is almost no difference with this one:

jQuery("#myDiv").append("<div>" + markup + "</div>");

The reason, I think the first scenario would be the slowest, is that you are creating the jQuery object 100 times rather than once.

Of course, it's always best to profile or otherwise test performance issues. Check out John Resig's Deep Profiling jQuery apps post.

Lance Fisher
Great response. Thanks. Will test that.
Ben
Except you're wrong. Don't just guess, always test. It even rhymes, lol :)
galambalazs
A: 

look on this link to improve your jquery

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

special tip 6 and 7

so the better from the list is :

//
var i, markup = "";
for (i=0; i<100; i++) {
    markup += "<span>" + i + "</span>";
}

//
jQuery("#myDiv").append("<div>" + markup + "</div>");
Haim Evgi
+2  A: 

It's very easy to test:

  1. Third one is the fastest because jQuery will have a wrapper element, only this needs to be attached to the parent and it's done. It's 3-5x faster then the other two.

  2. First one will be the second because jQuery appends every element directly without the overhead of handling big strings.

  3. Second one will be the slowest because after the giant string has been created it will have no root element, so the <span>s will be added one-by-one to the parent.

note: The actual order of the last two may vary in different browsers. They are somewhat identical.

galambalazs