$ .each () vs for () - and performance

These are basically just some of the things that I was interested in, maybe someone can give me a little more information about them, I will share what I have noticed so far!

The first thing I was wondering ... is there any difference or reason to use:

$('element').each(function (i, el) { });

- against -

$.each($('element'), function (i, el) { });

Looking at jQuery docs, I don't see any rhymes or reasons for one or the other (maybe you know an instance or additional things that can be done with each other.

But, more importantly, speed bothers me here

 // As opposed to $.each() looping through a jQuery object // -- 8x faster for (var i = 0, $('.whatever').length; i < len; i++) { $('.whatever')[i] // do stuff } 

If you look at jsFiddle DEMO here , you will see that the difference in speed is basically equivalent to any of them, but more importantly, I feel I should always use for() loops ...

I was just unit testing (looping through each of 5 different script functions, 50,000 times), just sorting through a bunch of list items and installing data-newAttr , nothing special.




QUESTION:: I think my biggest question is: why is it not always used for loops, iterating through an object? Does it make sense to use $ .each ()? Do you always use for () loops even when passing through jQuery objects?

jsFiddle DEMO here

 Function type: Execution Time: _testArea.each() + $(this) 1947 <-- using $(this) slows it down tremendously $.each() + $(this) 1940 _testArea.each() + el(plain JS) 458 <-- using the Element speeds things up $.each() + el(plain JS) 452 for() loop + plainJS[0] iteration 236 <-- over 8x faster 

Just my 2cents. :)

+60
javascript jquery
Aug 09 '12 at 16:05
source share
6 answers

One thing .each() allows you to do that cannot be done with a for loop is a chain .

 $('.rows').each(function(i, el) { // do something with ALL the rows }).filter('.even').each(function(i, el) { // do something with the even rows }); 



I played with my JSFiddle to see how the chain will affect performance when you need to iterate over subsets of the original set of matched elements.

The result was not so unexpected, although I think the overhead of end() was exaggerated here due to a combination of several elements and many loops. Other than that: simple JS loops are still a little faster, but it depends on whether this .each() readability of .each() (and the chain) more readable.

+39
Aug 09 '12 at 16:11
source share

One thing you get with .each() is automatic local scope detection (because you call an anonymous function for each object), which in turn means that you create even more anonymous functions / closures / handlers events / regardless of each iteration, you never have to worry about your handlers using the variable. That is, JavaScript does not act like other languages ​​when it comes to local areas, but since you can declare a variable anywhere, it can sometimes trick you.

In other words, this is not true:

 var idx,el; for (idx = 0; idx <someObjectArray.length; idx++){ el = someObjectArray[idx] el.someEventHandler(function(){ alert( "this is element " + idx); }); } 

Whenever any of these objects calls its "someEvent" after this loop (note that this is done), the warning will always report that the last idx was assigned, which should be (from the time it is called) someObjectArray.length ;

To maintain the correct index, you must declare a local scope, create a variable, and assign this variable to use.

 var idx,el; for (idx = 0; idx <someObjectArray.length; idx++){ el = someObjectArray[idx]; (function(){ var localidx = idx; el.someEventHandler(function(){ alert( "this is element " + localidx); }); })(); } 

As you can see, this is as ugly as hell, but it should work. Each event handler gets its own copy of localidx

Now compare this to .each()

 $(someObjectArray).each(function (idx, el) { el.someEventHandler(function(){ alert( "this is element " + idx); }); }); 

A lot easier, isn't it?

+20
Aug 09 '12 at 16:28
source share

jQuery.each vs for-loop

Benefits of jQuery.each:

  • Fits well in jQuery code (chain and style).
  • Do not worry about volume (iterator and object references will be constant).
  • It can be used everywhere (for all kinds of objects and iterating over object keys).

Benefits for the cycle:

  • High performance (for games / animations / large data sets).
  • Full control over the iterator (skip items, merging items from a list, etc.).
  • For-loop will always work because there is no jQuery dependency.
  • The same familiar syntax as most other similar languages.

Code example

This is a sample code of how I prefer to iterate over a list.

 var list = ['a', 'b', 'c', 'd', 'e', 'f']; 

jQuery.each:

 $.each(list, function(i, v) { // code... }); 

For a loop without a loop:

 for(var i=0,v,n=list.length;i<n;i+=1) { v = list[i]; // code... } 

Per loop cycle:

 for(var i=0,n=list.length;i<n;i+=1) { (function(i, v) { // code... })(i, list[i]); } 

Note. I suggest you use the standard for-loop and only use closure if necessary. However, when your code is more like jQuery than Javascript, it would be easier to just use $.each . In case of performance problems, you can always study it later.

+6
Sep 10 '14 at 10:56
source share

When I went to your link, here are the two numbers I received:

 $.each() + el(plain JS) 401 for() loop + plainJS[0] iteration 377 

If the difference is that it is small, then go to the one that is most readable, but if you have very high requirements for time, you just need to go with what will ultimately be the fastest.

I would suggest you write your program to use the three different methods, the two above, and then use the foreach found in new versions of javascript, and for those browsers that do not support it, you can add it as a prototype.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach

You know what your requirements are and what your program will do, so just write your own tests and make sure they meet the requirements in the browsers that you will support.

For your first question, I would go with $('element').each , since it is much easier to read, but this is just my opinion.

+4
Aug 09 '12 at 16:17
source share

I used to run some simple performance tests http://jsperf.com/forloops3 . It seems that sticking with the simple, old for loop (where possible) is the way to go :)

+4
Dec 28
source share

Actually there is a big difference between $ .each () and $ (). each ().

They do slightly different things depending on what you go through.

http://api.jquery.com/each/ vs http://api.jquery.com/jquery.each/

jquery.each is a generic iterator where $ () is. each () is specific to the jquery collection.

Also see: http://jsperf.com/each-vs-each-vs-for-in/9

0
Oct 24 '13 at 0:26
source share



All Articles