custom array forEach (v12)

Revision 12 of this benchmark created by termi on


Setup

var array=["foo","bar","baz","lorem","ipsum","lol","cat"];
  
  var func=function(){2+2};
  
  Array.prototype.forEach2=function(a){
    var l=this.length;
    for(var i=0;i<l;i++)a(this[i],i)
  }
  
  Array.prototype.map2=function(a){
  var l=this.length;
  var array=new Array(l),i=0;
  for(;i<l;i++){array[i]=a(this[i],i)}
  return array;
  }
  
  var setPrototypeOf = Object.setPrototypeOf || function(o, p){
  	o.__proto__ = p;
  	return o;
  };
  
  var TrueCustomArray = function () {
  	var array = new (Function.prototype.bind.apply(Array, [null].concat([].slice.call(arguments))));
  	setPrototypeOf(array, this.__proto__);
  	return array;
  };
  
  TrueCustomArray.prototype = Object.create(Array.prototype, { constructor: { value: TrueCustomArray } });
  TrueCustomArray.prototype.append = function(var_args) {
  	var_args = this.concat.apply([], arguments);        
  	this.push.apply(this, var_args);
  
  	return this;
  };
  TrueCustomArray.prototype.prepend = function(var_args) {
  	var_args = this.concat.apply([], arguments);
  	this.unshift.apply(this, var_args);
  
  	return this;
  };
  ["concat", "reverse", "slice", "splice", "sort", "filter", "map"].forEach(function(name) {
  	var _Array_prototype = this;
  	TrueCustomArray.prototype[name] = function() {
  		var result = _Array_prototype[name].apply(this, arguments);
  		setPrototypeOf(result, this.__proto__);
  		return result;
  	}
  }, Array.prototype);
  
  var customArray = new TrueCustomArray("foo","bar","baz","lorem","ipsum","lol","cat");

Test runner

Ready to run.

Testing in
TestOps/sec
for
(function(){
for(var i=array.length;i--;)2+2;
})()
ready
foreach
array.forEach(func)
ready
custom foreach
array.forEach2(func)
ready
map
array.map(func)
ready
custom map
array.map2(func)
ready
custom array for
(function(){
for(var i=customArray.length;i--;)2+2;
})()
ready
custom array foreach
customArray.forEach(func)
ready
custom array custom foreach
customArray.forEach2(func)
ready
custom array map
customArray.map(func)
ready
custom array custom map
customArray.map2(func)
ready

Revisions

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