We often write callbacks through anonymous functions.
Simply put, anonymous means a function without a name, is usually executed immediately. But how does it perform with named functions (functions with names)?
We can compare it. We can find a computer that can execute shell commands to use a large number of function calls to see how the execution time is consumed by the two:
Copy the codeThe code is as follows:
var count = 100000000
, sum = 0
while (count--) (function() { sum++ })()
Execute it
Copy the codeThe code is as follows:
$ time node
real 0m1.456s
user 0m0.015s
sys 0m0.031s
Let's take a look at named functions
Copy the codeThe code is as follows:
var count = 100000000
, sum = 0
var cb = function() {
sum++
}
while (count--) cb()
Execute it
Copy the codeThe code is as follows:
$ time node
real 0m0.575s
user 0m0.000s
sys 0m0.046s
Named functions will be much faster, why is this happening? In fact, it is not difficult to explain. Anonymous functions need to reinterpret the callback every time, but the 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, and there is no need to write a very convenient callback into another variable separately.
There are two ways to write named functions:
Function expressions
Copy the codeThe code is as follows:
var func = function() {
('a')
}
Function declaration
Copy the codeThe code is as follows:
function func() {
('b')
}
Actually, if these two are used together, there may be problems, such as
Copy the codeThe code is as follows:
var func = function() {
('a')
}
function func() {
('b')
}
//The output is: a
Therefore, currently, the form of function expressions is mostly used, but how is the performance of function declarations?
Copy the codeThe code is as follows:
var count = 100000000
, sum = 0
function cb() {
sum++
}
while (count--) cb()
Execute it and compare the two
Copy the codeThe code is as follows:
$ time node
real 0m0.553s
user 0m0.000s
sys 0m0.015s
$ time node
real 0m0.529s
user 0m0.000s
sys 0m0.047s
It seems that the function declaration will be a little faster, but it is very, very insignificant. I personally recommend the function declaration writing method.
PS: This data is tested using git-base under Windows 7.