Reputation: 273
I am developing an app in node js. I was using anonymous functions for callback purpose. Then I referred callbackhell.com site where I found writing named function is best way for coding.
But when I started writing code in named function format, my lines of code increased, my functions count increased. Is it better to write named function for every single callback.
Performance wise which is better?
Upvotes: 1
Views: 753
Reputation: 10454
While you may add more lines to your code, function declaration is the fastest. This particularly applies to instances where you are invoking the same function multiple times. Ex. collection lookups, array iteration, etc...
Using Benchmark.js, you can quickly see the difference.
☃ seth:~/Node/function-performance$ node test.js
Anonymous x 121 ops/sec ±8.31% (64 runs sampled)
Function Expression x 137 ops/sec ±5.25% (72 runs sampled)
Function Declaration x 165 ops/sec ±0.84% (86 runs sampled)
Fastest is Function Declaration
This is using the following code to test:
"use strict";
var Benchmark = require('benchmark')
var suite = new Benchmark.Suite
var stuff = [1,2,3,4,5,6,9,8,9,10,11,12,13,14,15];
var myEventHandler = function() {
// do something
};
function myEventHandler2() {
// do something
};
suite.add('Anonymous', function() {
for (var i = 0; i < 10000; ++i) {
stuff.forEach(function() {
// do something
});
}
})
.add('Function Expression', function() {
for (var i = 0; i < 10000; ++i) {
stuff.forEach(myEventHandler);
}
})
.add('Function Declaration', function() {
for (var i = 0; i < 10000; ++i) {
stuff.forEach(myEventHandler2);
}
})
.on('cycle', function(e) {
console.log(String(e.target))
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'))
})
.run({ 'async': true });
The same also goes for the browser.
To support Zeeker's comment - In the event you're not running the function more than once in a given instance, you can usually get away with anonymous functions, however it can clean up your invocations when using function declarations.
Upvotes: 3