Iterating array of elements

Benchmark created by David Mark on


Description

Typical jQuery pattern is: find some elements, do something to them. As seen here, the process if painfully slow in jQuery.

Some will say you should learn an alternate, obscure jQuery $.* syntax for "optimization". Then you lose all semblance of readability and the much-stressed "conciseness". Why bother with it at that point?

If you start calling $.* methods, you are basically using something similar to the My Library API interface (that jQuery devotees claim to "hate"). Difference is you can't do most things that way in jQuery. And let's face it, that's not how most jQuery code is written. All about the "chaining", isn't it? :)

jQuery is meant for advertising agencies to create interactive mockups, not for writing production browser scripts. This is useful as advertising agencies don't normally employ JS programmers. I've yet to see a jQuery-based anything that was fit to put on a Website.

Learn to write efficient JS instead. It's far more readable and much better documented. Faster too; users will thank you, especially mobile. ;)

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
/*
 * Context here is an HTML5 document
 * Appropriate build for this context would exclude XHTML support
 * Next line asserts document will create an HTML DOM
 * There are virtually no documents on the Web that create an XHTML DOM
 *
 */
var API = { disableXmlParseMode:true };
</script>
<script src="//www.cinsoft.net/mylib099-min.js"></script>
<script>
  // For My Library test
  
  var forEach = API.forEach;
  
  // For cross-browser test
  
  // Degrades below IE 5.5 (or anything else missing call method)
  // Remove else case to degrade in browsers lacking native forEach
  
  // NOTE: This forEach wrapper is *not* to be used with sparse arrays
  // Happily, queries produce no sparse arrays. :)
  
  var forEachElement;
  var myElements = [document.documentElement, document.body];
  
  if (Array.prototype.forEach) {
    forEachElement = function(elements, callback, thisObject) {
      elements.forEach(callback, thisObject);
    };
  } else if (Function.prototype.call) {
    forEachElement = function(elements, callback, thisObject) {
      for (var i = 0, l = elements.length; i < l; i++) {
        callback.call(thisObject, elements[i], i, elements);
      }
    };
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
My Library
forEach(myElements, function(el) {
  var id = el.id;
});
ready
jQuery
jQuery(myElements).each(function(el) {
  // Often seen as "$(el).attr('id')" :)
  var id = el.id;
});
ready
Cross-browser
if (forEachElement) {
  forEachElement(myElements, function(el) {
    var id = el.id;
  });
} else {
  throw new Error('Abort due to degraded browser');
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by David Mark on