Skip to content

Instantly share code, notes, and snippets.

@hinell
Created April 16, 2017 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hinell/8a5eb8020e6288b23fdab68400201cb2 to your computer and use it in GitHub Desktop.
Save hinell/8a5eb8020e6288b23fdab68400201cb2 to your computer and use it in GitHub Desktop.
Benchmark measures speed of every possible looping operators in javascript (i.e.: for(.;.;.),for of, for in, native .forEach() ) over Array and Map instance
console.clear && console.clear();
Array.prototype.each = function (fn,this_){
if(this.length <=0 || fn == undefined) return;
let i = -1
if (this_) fn = fn.bind(this_);
do { fn(this[i],i) }
while (i++ < this.length)
};
var pow = 16
var arr = Array.apply(null,{length: Math.pow(2,pow)}).map((e,i) => ['elem '+i,i]);
var fn = function(elem,i){};
console.time('while')
var i = 0;
while (i < arr.length) { fn(arr[i],i++) }
console.timeEnd('while')
console.time('for of')
var elem = undefined
for (elem of arr) { fn(elem) }
console.timeEnd('for of');
console.time('for itar')
for (var i = 0;i < arr.length; i++) { fn(arr[i],i) }
console.timeEnd('for itar')
console.time('for in')
var elem = undefined
for (elem in arr) { fn(arr[elem]) }
console.timeEnd('for in')
console.time('arr.forEach')
arr.forEach(fn);
console.timeEnd('arr.forEach')
console.time('arr.each')
arr.each(fn);
console.timeEnd('arr.each')
var m = new Map(arr);
console.time('Map while')
var entries = m.entries()
var done = false;
var pair;
while(!done) {
pair = entries.next();
done = pair.done
}
console.timeEnd('Map while')
console.time('Map forEach')
m.forEach(fn)
console.timeEnd('Map forEach')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment