12

A couple questions:

  1. Is a regular javascript loop (to loop through a series of elements) faster/more efficient than using jQuery each() ??

  2. If so, what is the best way to write the following code as a regular javascript loop?

$('div').each(function(){ //... })

Aziz Shaikh
  • 16,245
  • 11
  • 62
  • 79
HandiworkNYC.com
  • 10,914
  • 25
  • 92
  • 154
  • If you're really interested in loop efficiency, have a look here. http://stackoverflow.com/questions/1340589/javascript-are-loops-really-faster-in-reverse – James Montagne Aug 24 '12 at 21:51
  • 1
    A `for` loop is faster, but note that if what you're doing within the loop involves callback functions that need to use the loop index variable later then you would need to introduce a closure and that would (more or less) cancel out the efficiency gains. – nnnnnn Aug 24 '12 at 21:54

4 Answers4

14

Yes, removing the each() will give you slightly better performance. This is how you could write a for loop for a list of elements.

var divs = $('div');

for(var i = 0; i < divs.length; i++){
    var thisDiv = divs[i]; // element

    var $thisDiv = $(divs[i]); // jquery object

    // do stuff
}
Gabe
  • 49,577
  • 28
  • 142
  • 181
5
var divs = document.getElementsByTagName('div'),
    l = divs.length, i, cur;

for(i=0; i<l; i++) {
    cur = divs[i];
    // do stuff with cur here
}

Please continue on your path to removing jQuery in the name of efficiency. This code is approximately fifty times faster than the jQuery equivalent.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 5
    It's only 50x faster if you have nothing in the "do stuff with cur here" part. It's faster, but the 50x is misleading in the grand scheme. – James Montagne Aug 24 '12 at 21:45
1

To answer your second question, due to the first already being answered;

I was also interested in this, and I decided to benchmark the two to find the difference using Gabe's example. The answer is, in circumstances of wanting a jQuery object as the final result:

They perform exactly the same.

http://jsperf.com/jquery-each-vs-native-selectors

Firefox actually finds the jQuery version faster, apparently.

Voltlight
  • 136
  • 6
1

Instead of using jquery .each()

$('div').each(function(){ //... })

You can use document.querySelectorAll(), then convert the HTMLCollection into a JavaScript array. Then you can map over the array of elements.

 const elems = document.querySelectorAll('.my-elements')
 const $elems = [].slice.call(elems)
 $elems.map( (elem) => { console.log(elem) })
svnm
  • 22,878
  • 21
  • 90
  • 105