Home >Web Front-end >JS Tutorial >Performance testing of anonymous and named functions in JavaScript_Basic knowledge

Performance testing of anonymous and named functions in JavaScript_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:37:171244browse

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

Copy code The code is as follows:

var count = 100000000
, sum = 0
while (count--) (function() { sum })()

Execute it
Copy code The code is as follows:

$ time node anonymous.js
real 0m1.456s
user 0m0.015s
sys 0m0.031s

Let’s take a look at named functions

named.js

Copy code The code is as follows:

var count = 100000000
, sum = 0

var cb = function() {
sum
}

while (count--) cb()


Execute it
Copy code The code is as follows:

$ 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

Copy code The code is as follows:

var func = function() {
console.log('a')
}

Function declaration
Copy code The code is as follows:

function func() {
console.log('b')
}

In fact, there may be problems if these two are used together, such as
Copy code The code is as follows:

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

Copy code The code is as follows:

var count = 100000000
, sum = 0

function cb() {
sum
}

while (count--) cb()


Execute it and compare the two
Copy code The code is as follows:

$ 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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn