JavaScript
Article

jQuery Speed Test: $(this) vs .get() vs .eq()

By Sam Deering

Each loop cache performance – test to see if grabbing the current element from inside the each is possible/faster from a cached array of elements. Namely $(this) vs .get() vs .eq() with .text() and textContent/innerText. Tests run with jQuery 1.9.1. Similar to: jQuery Speed Test: $(this).attr(“id”); vs this.id .

dom-cache-loop-111

  • .get() and .eq() both return a single “element” from a jQuery object array, but they return the single element in different forms.
  • .eq() returns it as a jQuery object, meaning the DOM element is wrapped in the jQuery wrapper, which means that it accepts jQuery functions.
  • .get() return a raw DOM element. You may manipulate it by accessing its attributes and invoking its functions as you would on a raw DOM element. But it loses its identity as a jQuery-wrapped object, so a jQuery function like .fadeIn won’t work.

Setup



  • list
    • nested 1
    • nested 2
    • nested 3
  • list
  • nested 1
  • nested 2
  • nested 3
  • list
    • nested 1
    • nested 2
    • nested 3
  • list
  • Tests

    $.each(MY_OBJECT.cache.n, function(i, v) 
    {
        MY_OBJECT.cache.s.text($(this).text());
    });
    
    
    $.each(MY_OBJECT.cache.n, function(i, v) 
    {
        MY_OBJECT.cache.s.text(MY_OBJECT.cache.n.eq(i).text());
    });
    
    
    $.each(MY_OBJECT.cache.n, function(i, v) 
    {
        MY_OBJECT.cache.s.text(MY_OBJECT.cache.n.get(i).textContent);
    });
    • http://www.facebook.com/arnold.t.smith Arnold T. Smith

      I look forward to your posts every morning. Thanks for the learning!

    Recommended
    Sponsors
    Because We Like You
    Free Ebooks!

    Grab SitePoint's top 10 web dev and design ebooks, completely free!

    Get the latest in JavaScript, once a week, for free.