Skip to content

Instantly share code, notes, and snippets.

@bttmly
Last active August 29, 2015 14:07
Show Gist options
  • Save bttmly/0663d4d0bb163ba10a14 to your computer and use it in GitHub Desktop.
Save bttmly/0663d4d0bb163ba10a14 to your computer and use it in GitHub Desktop.
own keys benchmarking
var Benchmark = require( 'benchmark' );
var len = process.argv[2] || 3;
var obj = {};
for ( var i = 0; i < len; i++ ) {
obj[i] = "value" + i;
}
function noop () {}
function forInKeys ( obj ) {
for ( var key in obj ) {
if ( obj.hasOwnProperty( key ) ) {
noop( key );
}
}
}
function forKeys ( obj ) {
var keys = Object.keys( obj );
var len = keys.length;
for ( var i = 0; i < len; i++ ) {
noop( keys[i] );
}
}
function forEachKeys ( obj ) {
Object.keys( obj ).forEach( noop );
}
var events = [];
var suite = new Benchmark.Suite();
suite
.add( "for keys", function () {
forKeys( obj );
})
.add( "for in & has own", function () {
forInKeys( obj );
})
.add( "keys forEach", function () {
forEachKeys( obj );
})
.on( 'start', function () {
console.log( 'Hang tight, running benchmarks...' );
})
.on( 'cycle', function ( event ) {
events.push( event );
process.stdout.write( '.' );
})
.on( 'complete', function () {
process.stdout.write( '\n' );
var runs = this.slice().sort( function ( a, b ) {
return a.hz - b.hz;
});
var fastest = runs.pop();
console.log( fastest.name + " is fastest." );
console.log( String( fastest ) );
var run, diff, pct;
while ( runs.length ) {
run = runs.pop();
diff = fastest.hz - run.hz;
pct = ( diff * 100 / fastest.hz ).toFixed( 2 );
console.log( run.name + " is " + pct + "% slower than fastest.");
console.log( String( run ) );
}
})
.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment