We often write callbacks through anonymous functions.
To put it simply, anonymous means a function without a name, which is usually executed immediately. But how does it perform compared to named functions (functions with names)?
We can compare. We can find a computer that can execute Shell commands and use a large number of function calls to see the execution time of the two:
anonymous.js
var count = 100000000
, sum = 0
while (count--) (function() { sum })()
Execute it
$ time node anonymous.js
real 0m1.456s
user 0m0.015s
sys 0m0.031s
Let’s take a look at named functions
named.js
var count = 100000000
, sum = 0
var cb = function() {
sum
}
while (count--) cb()
Execute it
$ time node named.js
real 0m0.575s
user 0m0.000s
sys 0m0.046s
Named functions are much faster, why is this? In fact, it is not difficult to explain. Anonymous functions need to reinterpret the callback every time, but named functions only need to be interpreted once, so the performance will be improved. However, the test found that this improvement is very, very small. There is no need to separate a very convenient callback. written as another variable.
In addition, there are two ways to write named functions:
Function expression
var func = function() {
console.log('a')
}
Function declaration
function func() {
console.log('b')
}
In fact, there may be problems if these two are used together, such as
var func = function() {
console.log('a')
}
function func() {
console.log('b')
}
//The output is: a
Therefore, the form of function expression is mostly used at present, but what is the performance of function declaration?
named2.js
var count = 100000000
, sum = 0
function cb() {
sum
}
while (count--) cb()
Execute it and compare the two
$ time node named.js
real 0m0.553s
user 0m0.000s
sys 0m0.015s
$ time node named2.js
real 0m0.529s
user 0m0.000s
sys 0m0.047s
It seems that function declaration will be slightly faster, but the speed is very, very unobvious. Personally, I still recommend writing function declaration.
PS: This data was tested using git-base under Windows 7.