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] ;

For Loop without Caching

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

Pre-calculated Length attempt


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

Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

  • http://danmathisen.com/ Dan

    I’d like to see these results without calculating length at every iteration.

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

    • http://jquery4u.com/ jQuery4u

      Much faster results mate, I’ve added it to the post. http://jsperf.com/jquery-each-vs-for-loop/214

      • http://danmathisen.com/ dmathisen

        Awesome. I wasn’t expecting that great an improvement. Thanks for trying it out.

  • Ray

    and how about using browser native array’s forEach ?

    • http://jquery4u.com/ jQuery4u

      It’s slower – see jsperf

  • FTM

    Preety much same as PHPs for and foreach loop.
    Good reading.

  • http://www.facebook.com/vladimir.kharlampidi Vladimir Kharlampidi

    This is an expected behavior, every native function will be faster than with jQuery wrapper. But disadvantage and advantage of jQuery .each is that it calls anonymous function. Of course it is not good for perfomance, but it is good from the point of view that code which executed is inside of its own scope. Sometimes it is very useful.

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.