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

Sam Deering
Share

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);
    });