Range for Loops

JavaScript performance comparison

Test case created by ie900

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  let count = 150;
  let blackhole = 0;
  
  function range_iter(count) {
  	return {
  		[Symbol.iterator]() {
  			return {
  				i: 0,
  				next() {
  					if(this.i >= count) {
  						return {done: true};
  					}
  					
  					return {done: false, value: this.i++};
  				}
  			}
  		}
  	}
  }
  
  class RangeIter {
  	constructor(count) {
  		this.count = count;
  	}
  	
  	[Symbol.iterator]() {
  		this.i = 0;
  		return this;
  	}
  	
  	next() {
  		if(this.i >= this.count) {
  			return {done: true};
  		}
  		
  		return {done: false, value: this.i++};
  	}
  }
  
  function range_gen(count) {
  	return {
  		*[Symbol.iterator]() {
  			for(let i = 0; i < count; ++i) {
  				yield i;
  			}
  		}
  	}
  }
  
  class RangeGen {
  	constructor(count) {
  		this.count = count;
  	}
  	
  	*[Symbol.iterator]() {
  		for(let i = 0; i < this.count; ++i) {
  			yield i;
  		}
  	}
  }
  
  function range_keys(count) {
  	return Array(count).keys();
  }
  
  class RangeKeys {
  	constructor(count) {
  		this.count = count;
  	}
  	
  	*[Symbol.iterator]() {
  		return Array(this.count).keys();
  	}
  }
  
  function range_arr(count) {
  	let array = new Array(count);
  	for(let i = 0; i < count; ++i) {
  		array[i] = i;
  	}
  	
  	return array;
  }
  
  function range_call(count, fun) {
  	for(let i = 0; i < count; ++i) {
  		fun(i);
  	}
  }

};
</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
range (function iteration)
for(let i of range_iter(count)) {
	blackhole += i;
}
pending…
range (class iteration)
for(let i of new RangeIter(count)) {
	blackhole += i;
}
pending…
range (function generator)
for(let i of range_gen(count)) {
	blackhole += i;
}
pending…
range (class generator)
for(let i of new RangeGen(count)) {
	blackhole += i;
}
pending…
range (from array keys) (function)
for(let i of range_keys(count)) {
	blackhole += i;
}
pending…
range (from array keys) (class)
for(let i of new RangeKeys(count)) {
	blackhole += i;
}
pending…
range (from range array)
for(let i of range_arr(count)) {
	blackhole += i;
}
pending…
loop
for(let i = 0; i < count; ++i) {
	blackhole += i;
}
pending…
range (callback)
range_call(count, i => {
	blackhole += i;
});
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