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();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
eval | |
new Function |
Test name | Executions per second |
---|---|
eval | 3734688.2 Ops/sec |
new Function | 5360293.5 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark is comparing two approaches: eval
and new Function
. The goal is to measure which approach is faster, more efficient, or has better performance characteristics.
Options Compared
Two options are being compared:
eval
: A built-in JavaScript function that evaluates a string as JavaScript code.new Function
: A constructor function used to create a new function object. The syntax new Function("code")
creates a new function with the specified code.Pros and Cons of Each Approach
eval
:eval
can also introduce security risks if used with untrusted input.new Function
:eval
, as it avoids the risk of executing arbitrary code.Library Usage
In this benchmark, the Function
constructor is used to create a new function object. This is a built-in JavaScript library, and its purpose is to provide a way to dynamically create function objects from strings or other data sources.
Special JS Feature/Syntax
There are no special JavaScript features or syntaxes being used in these test cases. The benchmark focuses on the performance comparison between eval
and new Function
.
Other Alternatives
If you're interested in exploring alternative approaches for executing code, here are a few options:
Function.prototype.toString()
: This method returns a string representation of the function, which can be used to create a new function object.bind()
or call()
methods: These methods allow you to invoke functions with specific arguments and contexts.However, these alternatives are not being compared in this benchmark.
Benchmark Preparation Code
The preparation code for each test case is provided:
eval
test case: let r = Math.random().toString(36).substring(7).includes('x');
new Function
test case: var newFunc = new Function("let r = Math.random().toString(36).substring(7).includes('x');");
These code snippets are used to define a simple expression that tests the performance of each approach.
Latest Benchmark Result
The latest benchmark results show:
new Function
test case: 438,8521.5 executions per secondeval
test case: 178,9463.375 executions per secondThese results suggest that new Function
is significantly faster than eval
in this specific benchmark scenario.
I hope this explanation helps you understand what's being tested in this benchmark!