var f = "() => 'yo'"
eval(f);
Function(`"use strict";return ${f}`)()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
eval | |
new Function |
Test name | Executions per second |
---|---|
eval | 1990942.1 Ops/sec |
new Function | 993341.8 Ops/sec |
Let's dive into the provided benchmark and explain what is being tested.
Benchmark Purpose
The benchmark measures the performance difference between two approaches: using the eval()
function and creating a new anonymous function using the Function()
constructor.
Options Compared
Two options are compared:
eval(f);
: This approach uses the built-in eval()
function to execute the provided string as JavaScript code. The string f
is defined in the Script Preparation Code section of the benchmark definition and contains an arrow function.Function(
"use strict";return ${f})()
: This approach creates a new anonymous function using the Function()
constructor. The string f
is passed as an argument to the constructor, which returns the created function. The function body is wrapped in an immediately invoked expression (IIFE) to ensure it's executed immediately.Pros and Cons of Each Approach
eval(f);
:Function(f)();
:eval()
, reducing security risks.eval()
.Library Usage
There is no explicit library usage in this benchmark, but it's worth noting that some modern JavaScript implementations (e.g., V8) provide optimized functions like Function()
that can outperform traditional Function()
constructors.
Special JS Features or Syntax
The benchmark does not use any special JavaScript features or syntax. However, the use of arrow functions (() => 'yo'
) is a relatively recent feature introduced in ECMAScript 2015 (ES6).
Alternative Approaches
Other approaches to create and execute anonymous functions could be used instead of eval()
or the Function()
constructor:
with
statement: Not recommended due to its legacy nature and performance issues.eval()
with a with
clause: Similar to using with
alone, but still carries security risks.new Function(f)
: Another approach to create an anonymous function, which can be more efficient than the traditional Function()
constructor.Keep in mind that these alternatives might not provide identical performance characteristics as the benchmarked approaches.