Skip to main content

Speed Question jQuery.each vs. for loop

By Sam Deering



Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

Quick point. It might be beneficial to mention that we are using vanilla for loops instead of jQuery.each for speed (up to 84% faster). Using a for loop with variable caching produces even faster results jsperf – each vs for.



$.each(a, function() {
  e = this;

For Loop with Caching

for ( var i = 0, len = a.length; i < len; i++) { e = a[ i] ; }; [/js]

For Loop without Caching

for (var i = 0; i < a.length; i++) {   e = a[i]; }; [/js]

Pre-calculated Length attempt


var len = a.length, i = 0;
for (i; i < len; i++) { e = a[i]; }; [/js]

Related Articles

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn the basics of programming with the web's most popular language - JavaScript

A practical guide to leading radical innovation and growth.

Integromat Tower Ad