How to remove uninitialized objects from an array

JavaScript performance comparison

Test case created by Stan Omoregie

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var initId = 4,    
      removedObjects = [],
      description = '',
      objectArray = [{Id: 1, isObsolete: false, Name: "Yellow"},
                     {Id: 2, isObsolete: true, Name: "Green"},
                     {Id: 3, isObsolete: false, Name: "Blue"},
                     {Id: 4, isObsolete: true, Name: "Purple"},
                     {Id: 5, isObsolete: false, Name: "Black"}];
  
  function forEachLoopObjectRemoval(obj, sId) {
     var removedObjA = [];
     description = 'forEachLoopObjectRemoval: ';
     obj.forEach(function (sub, i) {
        if (sub.isObsolete === true && sub.Id !== sId) {
           removedObjA.push(sub);
           obj.splice(i, 1);
        }
     });
     return removedObjA;
  }
  
  function forLoopObjectRemoval(obj, sId) {
     var removedObjB = [];
     description = 'forLoopObjectRemoval: ';
     for (var j = 0; j < obj.length; j++) {
        if (obj[j].isObsolete === true && obj[j].Id !== sId){
           removedObjB.push(obj[j]);
           obj.splice(j, 1);
           j--;
        }
     }
     return removedObjB;
  }
  
  function whileLoopObjectRemoval(obj, sId) {
     var removedObjC = [];
     description = 'whileLoopObjectRemoval: ';
     var keys = Object.keys(obj), i = keys.length;
     while (i--) {
        if (obj[i].isObsolete === true && obj[i].Id !== sId) {
            removedObjC.push(obj[i]);
            obj.splice(i, 1);
        }
     }
     return removedObjC;
  }

};

Benchmark.prototype.teardown = function() {
  //console.log(description, JSON.stringify(removedObjects));

};
</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
ForEach-Loop
removedObjects = forEachLoopObjectRemoval(objectArray, initId);
pending…
For-Loop
removedObjects = forLoopObjectRemoval(objectArray, initId);
pending…
While-Loop
removedObjects = whileLoopObjectRemoval(objectArray, initId)
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