Range for Loops

Benchmark created by ie900 on


Setup

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);
  	}
  }

Test runner

Ready to run.

Testing in
TestOps/sec
range (function iteration)
for(let i of range_iter(count)) {
	blackhole += i;
}
ready
range (class iteration)
for(let i of new RangeIter(count)) {
	blackhole += i;
}
ready
range (function generator)
for(let i of range_gen(count)) {
	blackhole += i;
}
ready
range (class generator)
for(let i of new RangeGen(count)) {
	blackhole += i;
}
ready
range (from array keys) (function)
for(let i of range_keys(count)) {
	blackhole += i;
}
ready
range (from array keys) (class)
for(let i of new RangeKeys(count)) {
	blackhole += i;
}
ready
range (from range array)
for(let i of range_arr(count)) {
	blackhole += i;
}
ready
loop
for(let i = 0; i < count; ++i) {
	blackhole += i;
}
ready
range (callback)
range_call(count, i => {
	blackhole += i;
});
ready

Revisions

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