Skip to content

Instantly share code, notes, and snippets.

@moshen
Last active October 7, 2015 15:29
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 moshen/35e440d2a2e81ca08464 to your computer and use it in GitHub Desktop.
Save moshen/35e440d2a2e81ca08464 to your computer and use it in GitHub Desktop.
binding this vs creating an anonymous function
var Benchmark = require('benchmark'),
suite = new Benchmark.Suite;
var obj = {
name: 'myobj',
meth: function() {
return this.name;
}
};
var anon = function() {
obj.meth();
}
var bound = obj.meth.bind(obj);
suite.add('anon-function-in-iter', function() {
(function() {
obj.meth();
})();
})
.add('bind-function-in-iter', function() {
obj.meth.bind(obj)();
})
suite.add('anon-function-once', function() {
anon();
})
.add('bind-function-once', function() {
bound();
})
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
})
.run();
{
"name": "node-function-speed-tests",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"benchmark": "^1.0.0"
},
"devDependencies": {},
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "MIT"
}
@moshen
Copy link
Author

moshen commented Sep 4, 2015

Clone with: git clone git@gist.github.com:35e440d2a2e81ca08464.git node-function-speed-tests

My results:

anon-function-in-iter x 28,976,729 ops/sec ±0.68% (100 runs sampled)
bind-function-in-iter x 1,213,125 ops/sec ±0.71% (96 runs sampled)
anon-function-once x 59,548,241 ops/sec ±1.14% (94 runs sampled)
bind-function-once x 6,256,005 ops/sec ±2.37% (87 runs sampled)
Fastest is anon-function-once

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment