Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

javascript - $().each vs $.each vs for loop in jQuery?

I Can't understand why it is happening.

I read here that :

The first $.each constitutes a single function call to start the iterator.

The second $(foo.vals).each makes three function calls to start the iterator.

  • The first is to the $() which produces a new jQuery wrapper set (Not sure how many other function calls are made during this process).
  • Then the call to $().each.
  • And finally it makes the internal call to jQuery.each to start the iterator.

In your example, the difference would be negligible to say the least. However, in a nested use scenario, you might find performance becoming an issue.

Finally, Cody Lindley in jQuery Enlightenment does not recommend using $.each for iterations greater than 1000 because of the function calls involved. Use a normal for( var i = 0... loop.

So I tested it with this jsperf :

(task : find Tr's who has checked checkbox inside of them , and color that tr.)

This is the jsbin

But look at jsperf

against all expectations , the opposite is the true. ( chrome and FF and IE)

enter image description here

The one who uses $().each ( which calls three methods is the fastest and etc..

What is going on here?

question from:https://stackoverflow.com/questions/14808144/each-vs-each-vs-for-loop-in-jquery

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your test is too heavy to really determine the actual difference between the three looping options.

If you want to test looping, then you need to do your best to remove as much non-related work from the test as possible.

As it stands, your test includes:

  • DOM selection
  • DOM traversal
  • element mutation

All of those are quite expensive operations compared to the loops themselves. When removing the extra stuff, the difference between the loops is much more visible.

http://jsperf.com/asdasda223/4

In both Firefox and Chrome, the for loop is well over 100x faster than the others.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...