Code questions for Jquery
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>");
//
It's very easy to test:
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.
First one will be the second because jQuery appends every element directly without the overhead of handling big strings.
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.
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.
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);
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>");
精彩评论