arrays with and without holes

JavaScript performance comparison

Test case created by Justin Force

Info

Is it better to spend time up front constructing arrays of objects without holes? Or to just check for holes when you iterate?

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
 
<script>
Benchmark.prototype.setup = function() {
    var simple = [], complex = [],
      selectIndexes = [1, 2, 10, 14, 300, 1000],
      pairs = [
        { "id" : 1,
          "name" : "Albert"
        },
        { "id" : 2,
          "name" : "Bailey"
        },
        { "id" : 4,
          "name" : "Charlotte"
        },
        { "id" : 5,
          "name" : "Darlene"
        },
        { "id" : 10,
          "name" : "Edna"
        },
        { "id" : 12,
          "name" : "Faron"
        },
        { "id" : 13,
          "name" : "Gary"
        },
        { "id" : 14,
          "name" : "Helen"
        },
        { "id" : 15,
          "name" : "Igor"
        },
        { "id" : 16,
          "name" : "Justin"
        },
        { "id" : 17,
          "name" : "Kyle"
        },
        { "id" : 300,
          "name" : "Lynette"
        },
        { "id" : 500,
          "name" : "Morgan"
        },
        { "id" : 1000,
          "name" : "Nora"
        }
      ],
   
      get = function (a, i) {
        var ret = null;
        $.each(a, function () {
          if (this.id === i.valueOf()) {
            ret = this;
          }
        });
        return ret;
      };
};

Benchmark.prototype.teardown = function() {
    simple = [], complex = [];
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
simple
$.each(pairs, function () {
  simple[this.id] = this.name;
});

$.each(simple, function () {
  if (this && this !== window) {
    this.charAt(0);
  }
});

$.each(selectIndexes, function () {
  simple[this].charAt(0);
});
pending…
complex
$.each(pairs, function () {
  complex.push(this);
});

$.each(complex, function () {
  this.name.charAt(0);
});

$.each(selectIndexes, function () {
  get(complex, this).name.charAt(0);
});
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