var test = function test() {
var x = 0;
var nested= function() {
for (var i=0; i< 10000000; i++) {
x = x + Math.random();
}
}
nested();
};
test();
(function () {
var x = 0;
var nested= function() {
for (var i=0; i< 10000000; i++) {
x = x + Math.random();
}
}
nested();
})();
(function test() {
var x = 0;
var nested= function() {
for (var i=0; i< 10000000; i++) {
x = x + Math.random();
}
}
nested();
})();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
1 | |
2 | |
3 |
Test name | Executions per second |
---|---|
1 | 0.6 Ops/sec |
2 | 0.5 Ops/sec |
3 | 0.5 Ops/sec |
I'd be happy to explain what's being tested in the provided benchmark.
Script Preparation Code and Benchmark Definition
The script preparation code is empty, which means that the JavaScript engine will generate the script dynamically when the benchmark runs.
The benchmark definition contains three different ways of defining a function:
var
function declaration: var test = function test() { ... }
var
: (function () { ... })()
var
: (function test() { ... })()
(note the missing var
keyword)Comparison of Options
The three options are being compared in terms of their performance.
var
function declaration, creates a new scope for the test
function and its inner function (nested
). This is a common way to define functions in JavaScript.var
, also creates a new scope, but it's done using a self-invoking anonymous function. This approach avoids polluting the global namespace with the test
variable.var
, does not create a new scope for the nested
function, which is defined inside the outer scope of the test
function. However, this is not a recommended way to define functions in JavaScript, as it can lead to unexpected behavior and security issues.Pros and Cons
var
function declaration:var
:var
:Library and Purpose
There are no libraries used in the benchmark definition. However, the benchmark results include information about the device platform, operating system, and browser version, which suggests that the tests were run on a mobile device with Firefox OS.
Special JavaScript Features or Syntax
None of the options use any special JavaScript features or syntax beyond what's standard.
Other Alternatives
If you wanted to test these scenarios in a different way, here are some alternatives:
const
instead of var
on function scope.Keep in mind that these alternatives might require modifications to the benchmark definition and script preparation code.