Best way to select an object into an array

JavaScript performance comparison

Test case created by Maxime Warnier

Preparation code

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
      
<script>
Benchmark.prototype.setup = function() {
  var array_test_length = 10000;
  var myTable = [];
  for (var i = 0; i < array_test_length; i++) {
    myTable.push({
      id: i,
      data: i.toString()
    });
  }
  var ElementId = 200;

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
for
for (var i = 0; i < myTable.length; i++) {
  if (myTable[i].id === ElementId) {
    break;
  }
}
pending…
for cached length
for (var i = 0, t = myTable.length; i < t; i++) {
  if (myTable[i].id === ElementId) {
    break;
  }
}
pending…
Array.forEach
myTable.forEach(function(val) {

  if (val.id === ElementId) {
    //myObject = val; no break for forEach
  }
});
pending…
Array.every
myTable.every(function(val) {
  if (val.id === ElementId) {
    //myObject =  val ;
    return false;
  }
  return true;
});
pending…
Array.some
myTable.some(function(val) {

    if (val.id === ElementId) {
         //myObject =  val ;
        return true;
    }
    return false;
});
pending…
Array.filter
myTable.filter(function (element) {
    return element.id === ElementId;
})[0];
pending…
lowDash find
_.find(myTable, function(element) {
  return element.id === ElementId;
});
pending…

Compare results of other browsers

Revisions

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

0 Comments