remove null items from array

JavaScript performance comparison

Test case created by vincent piel

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var removeNull = function() {
  	var nullCount = 0           ;
  	var length    = this.length ;
  	for (var i=0, len=this.length; i<len; i++) { if (!this[i]) {nullCount++} }
      // no item is null
  	if (!nullCount) { return this}
  	// all items are null
  	if (nullCount == length) { this.length = 0; return this }
  	// mix of null // non-null
  	var idest=0, isrc=length-1;
  	length -= nullCount ;				 
  	while (true) {
  			 	    while (!this[isrc])  { isrc--; nullCount--; } // find a non null (source) slot on the right
  			 		if    (!nullCount) { break }       // break if found all null
  			 		while ( this[idest]) { idest++  }  // find one null slot on the left (destination)
  					// perform copy
  			 		this[idest]=this[isrc];
  			 		if (!(--nullCount)) {break}
  			 		idest++;  isrc --; 
  				 }
  	this.length=length; 
  	return this;
  };	
  
  Object.defineProperty(Array.prototype, 'removeNull', { value : removeNull, writable : true, configurable : true } ) ;
  
  function identity(e) {return e };
  
  
  function cleanArray(actual){
    var newArray = new Array();
    for(var i = 0; i<actual.length; i++){
        if (actual[i]){
          newArray.push(actual[i]);
      }
    }
    return newArray;
  }
  
  Array.prototype.clean = function(deleteValue) {
    for (var i = 0; i < this.length; i++) {
      if (this[i] == deleteValue) {         
        this.splice(i, 1);
        i--;
      }
    }
    return this;
  };
  
  var testArray = [];
  var cnt       = 100 ;
  
  for (var i=0; i<cnt; i++) { testArray[i]= 0 | Math.random()*3 }

};
</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
removeNull custom function
testArray.removeNull();
pending…
using filter with an identity function
var arr = testArray.filter(identity); 
pending…
create a new array with push
var res = cleanArray(testArray);
pending…
using splice
testArray.clean(0);
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