开发者

Code questions for Jquery

开发者 https://www.devze.com 2023-01-23 00:11 出处:网络
Which code will work fastest? for(i=0; i<100; i++) { jQuery(\"#myDiv\").append(\"<span>\" + i + \"</span>\");

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:

  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.


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>");
0

精彩评论

暂无评论...
验证码 换一张
取 消