Skip to content

Instantly share code, notes, and snippets.

@southp
Created April 22, 2016 09:05
Show Gist options
  • Save southp/0ee7b2f13739ccd7a4dcf5938035b2cb to your computer and use it in GitHub Desktop.
Save southp/0ee7b2f13739ccd7a4dcf5938035b2cb to your computer and use it in GitHub Desktop.
"use strict";
const toMs = ( diff ) => {
return diff[ 0 ] * 1000 + diff[ 1 ] / 1000;
};
const SIZE = 1000000;
let arr = [];
for ( var i = 0; i < SIZE; ++i ) {
arr.push( Math.floor( Math.random() * 256 ) );
}
/////////////////// simple loop
let prev = process.hrtime();
let sum = 0;
for ( var i = 0; i < SIZE; ++i ) {
sum += arr[ i ];
}
let t0 = toMs( process.hrtime( prev ) );
console.log( "Time cost of simple loop: ", t0, sum );
////////////////// for ... in
prev = process.hrtime()
sum = 0;
for ( var i in arr ) {
sum += arr[ i ];
}
let t1 = toMs( process.hrtime( prev ) );
console.log( "Time cost of for ... in: ", t1, sum );
console.log( "ratio: ", t1 / t0 );
////////////////// for ... of
prev = process.hrtime()
sum = 0;
for ( var val of arr ) {
sum += val;
}
let t2 = toMs( process.hrtime( prev ) );
console.log( "Time cost of for ... of: ", t2, sum );
console.log( "ratio: ", t2 / t0 );
/////////////////// forEach
prev = process.hrtime()
sum = 0;
arr.forEach( function ( val ) {
sum += val;
} );
let t3 = toMs( process.hrtime( prev ) );
console.log( "Time cost of forEach: ", t3, sum );
console.log( "ratio: ", t3 / t0 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment