var newFunc = new Function("let r = Math.random().toString(36).substring(7).includes('x');");
eval("let r = Math.random().toString(36).substring(7).includes('x');");
newFunc();
let r = Math.random().toString(36).substring(7).includes('x');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
eval | |
new Function | |
func |
Test name | Executions per second |
---|---|
eval | 3129476.8 Ops/sec |
new Function | 4751857.0 Ops/sec |
func | 4726098.5 Ops/sec |
Let's break down the provided benchmark definition and test cases to understand what's being tested.
Benchmark Definition Json
The benchmark is designed to compare the performance of three different approaches:
new Function()
: This approach creates a new function using the Function
constructor, which takes a string of JavaScript code as an argument.eval()
: This approach uses the built-in eval()
function to execute a string of JavaScript code.let r = Math.random().toString(36).substring(7).includes('x');
(alias: func
): This is a simple JavaScript expression that generates a random string and checks if it includes the character 'x'
.Options Compared
The benchmark compares the performance of these three approaches:
new Function()
: Creating a new function using the Function
constructor.eval()
: Using the built-in eval()
function to execute JavaScript code.func
(simple expression): Executing a simple JavaScript expression.Pros and Cons
Here's a brief overview of the pros and cons of each approach:
new Function()
:eval()
, as it prevents access to the global object.eval()
:func
(simple expression):new Function()
or eval()
, which can execute arbitrary code.Library: None
There are no external libraries used in this benchmark. The test cases only rely on built-in JavaScript features.
Special JS Feature/ Syntax: None
There are no special JavaScript features or syntaxes being tested in this benchmark. It's focused on comparing the performance of different approaches to executing JavaScript code.
Alternatives
If you're looking for alternatives to this benchmark, here are a few options:
Function()
constructor: This is similar to new Function()
, but with a more concise syntax.Function Expression
: This is another way to create functions in JavaScript, using the syntax let func = function() { ... };
.Arbitrary Code Execution
: If you need to execute arbitrary code, you might consider using a framework like WebAssembly (WASM) or a sandboxed environment.Keep in mind that this benchmark is focused on comparing the performance of different approaches to executing JavaScript code. If your use case requires more complex scenarios, you may want to consider alternative benchmarks or testing frameworks.