Versatile iterator

JavaScript performance comparison

Test case created by Marco Dias Lopes

Info

Test a versatile iterator agains conventional iteration and a jQuery implementation.

Preparation code

<ul>
  <li>
    1
  </li>
  <li>
    2
  </li>
  <li>
    3
  </li>
  <li>
    4
  </li>
  <li>
    5
  </li>
  <li>
    6
  </li>
  <li>
    7
  </li>
  <li>
    8
  </li>
  <li>
    9
  </li>
  <li>
    10
  </li>
</ul>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
        o = {
        a: "a",
        b: "b",
        c: "c"
        },
        n = document.getElementsByTagName("li");
   
   
    function each(source, fHandler, oScope) {
      var i, li, A = Array.prototype;
      oScope = oScope || this;
   
      // handle an array or collection
      if (source instanceof Array || ((typeof source === "object" || source instanceof Object) && typeof source.length === "number")) {
        if (A.forEach) {
          A.forEach.call(source, fHandler, oScope);
        } else {
          for (i = 0, li = source.length; i < li; ++i) {
            fHandler.call(oScope, source[i], i, source);
          }
        }
        return true;
      } else if (source instanceof Object && typeof source !== "function") {
        for (i in source) {
          if (source.hasOwnProperty(i)) {
            fHandler.call(oScope, source[i], i, source);
          }
        }
        return true;
      }
   
      return false;
    };
    handler = function() {};
};
</script>

Preparation code output

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Each method
each(a, handler);
each(o, handler);
each(n, handler);
pending…
Conventional implementation
var i, li;
for (var i = 0, li = a.length; i < li; ++i) {
  handler.call(this, a[i]);
}
for (i in o) {
  if (o.hasOwnProperty(i)) {
    handler.call(this, o[i]);
  }
}
for (i = 0, li = n.length; i < li; ++i) {
  handler.call(this, n[i]);
}
pending…
jQuery
$.each(a, handler);
$.each(o, handler);
$.each(n, handler);
pending…

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

Compare results of other browsers

0 comments

Add a comment