Fastest way to loop through jQuery-returned DOM nodes

I got a very interesting, yet absolutely logical result while chilling on jsperf.

http://jsperf.com/for-in-jquery-return-value-vs-jquery-each

In a preparation environment, where O is jQuery return value of 200 DOM Nodes, and a is an empty array,

O.each(function() {
  a[a.length] = $(this).text();
});

is a LOT slower than this "pure" snippet

for (i = 0; i < O.length; i++) {
  a[a.length] = O[i].text();
}

( For the difference, check the link above )

Considering, that I was just having fun, there have to be even faster ways out there. What is the fastest way to loop through DOM elements using jQuery?

Upvotes: 1

Views: 1261

Answers (1)

brainless coder
brainless coder

Reputation: 6430

Well performed another test, seems that

http://jsperf.com/for-in-jquery-return-value-vs-jquery-each/2

for (i = 0; i < O.length; i++) {
  a[a.length] = O[i].text(); // tested this, because this is the usual way i work with pushing item to array
}

is even faster than -

for (i = 0; i < O.length; i++) {
  a.push($(O[i]).text());
}

I guess push itself is slower or removing extra $(..), removes some overhead.

EDIT:

enter image description here

Upvotes: 2

Related Questions