Note that there are some explanatory texts on larger screens.

plurals
  1. PO$.each() vs for() loop - and performance
    primarykey
    data
    text
    <p>These are mainly just some things I've been wondering, maybe someone can give me a little more insight on them, i'll share what i've noticed so far as well!</p> <p>First thing i've been wondering... is there any difference good or reason to use:</p> <p><code>$('element').each(function (i, el) { });</code> </p> <p>-- versus -- </p> <p><code>$.each($('element'), function (i, el) { });</code> </p> <p>Looking at the jQuery docs I can't see any rhyme or reason for one or the other (maybe you know an instance or additional things one can do over the other.</p> <p><strong>But more importantly I'm concerned with <em>speed</em> here</strong></p> <pre><code>// As opposed to $.each() looping through a jQuery object // -- 8x faster for (var i = 0, $('.whatever').length; i &lt; len; i++) { $('.whatever')[i] // do stuff } </code></pre> <p>If you check out this <strong><a href="http://jsfiddle.net/3ySng/1/" rel="noreferrer">jsFiddle DEMO here</a></strong>, you'll see the difference in speed is basically equivalent with either of them, but more importantly I feel like I should <em>always</em> be using <code>for()</code> loops...</p> <p>I was just unit testing (looping through each of 5 different scenario functions, 50,000 times), simply looping through a bunch of list items, and setting a <code>data-newAttr</code>, nothing special.</p> <hr> <p><strong>QUESTION :: I guess my biggest question is, why not <em>always</em> use for loops while iterating through an object?? Is there even a point to using $.each()? Do you always use for() loops even when going through jQuery objects?</strong></p> <p><strong><a href="http://jsfiddle.net/3ySng/1/" rel="noreferrer">jsFiddle DEMO here</a></strong></p> <pre><code>Function type: Execution Time: _testArea.each() + $(this) 1947 &lt;-- using $(this) slows it down tremendously $.each() + $(this) 1940 _testArea.each() + el(plain JS) 458 &lt;-- using the Element speeds things up $.each() + el(plain JS) 452 for() loop + plainJS[0] iteration 236 &lt;-- over 8x faster </code></pre> <p>Just my 2cents. :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload