Performance testing of anonymous named functions in JavaScript
- 2020-03-30 03:51:13
- OfStack
We often write callbacks via Anonymous function.
Simply put, anonymous is a function that has no name and is usually executed immediately. But how does it perform with named functions (functions with names)?
Let's compare that. Let's take a random computer that can execute Shell commands and use a lot of function calls.
Anonymous. Js
var count = 100000000
, sum = 0
while (count--) (function() { sum++ })()
To perform a
$ time node anonymous.js
real 0m1.456s
user 0m0.015s
sys 0m0.031s
Let's look at the naming function
Named. Js
var count = 100000000
, sum = 0
var cb = function() {
sum++
}
while (count--) cb()
To perform a
$ time node named.js
real 0m0.575s
user 0m0.000s
sys 0m0.046s
Naming functions is a lot faster. Why is that? It's not hard to explain. Anonymous functions need to reinterpret callbacks every time, but named functions only need to be reinterpreted once, so there's a performance boost.
In addition, there are two ways to write named functions:
Functional expression
var func = function() {
console.log('a')
}
Function declaration
function func() {
console.log('b')
}
In fact, there may be problems when these two are used together, such as
var func = function() {
console.log('a')
}
function func() {
console.log('b')
}
//The output is: a
So we use function expressions a lot, but what about the performance of function declarations?
Named2. Js
var count = 100000000
, sum = 0
function cb() {
sum++
}
while (count--) cb()
Execute 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 like the function declaration is going to be a little bit faster, but it's not too fast and it's not very, very obvious.
PS: this data is all tested with git-base under Windows7.