eval("2 * 3");
var func = new Function("return 2 * 3");
func();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
eval | |
new Function |
Test name | Executions per second |
---|---|
eval | 2498067.5 Ops/sec |
new Function | 209886.9 Ops/sec |
I'd be happy to help explain the JavaScript microbenchmark you've shared.
What is being tested?
MeasureThat.net is testing two different approaches for evaluating arithmetic expressions in JavaScript: eval()
and new Function()
. The benchmark compares the performance of these two methods in executing a simple arithmetic expression: 2 * 3
.
Options compared
The main options being compared are:
eval()
: A built-in JavaScript function that executes arbitrary code, including scripts and expressions.new Function()
: A constructor function that creates a new function object from a string of code.Pros and cons
eval()
: Pros:eval()
.eval()
can be slower than other methods due to its dynamic nature.eval()
can execute arbitrary code, making it a potential security risk if not used carefully.new Function()
: Pros:eval()
since it's just executing a simple function call.
Cons:Other considerations
eval()
or new Function()
. This refers to whether the JavaScript engine caches the results of parsing an expression after it's been executed once. If caching occurs, re-executing the same expression may be faster.Library and syntax
There are no external libraries used in these benchmarks. However, new Function()
relies on JavaScript's built-in Function
constructor, which is a standard feature in most modern browsers.
Special JS features or syntax
None of the benchmarking approaches rely on any special JavaScript features or syntax that would be unusual to encounter in everyday coding. The code snippets are straightforward and easy to understand.
Alternatives
If you're looking for alternative methods to evaluate expressions, consider:
let
expression: A newer feature introduced in ECMAScript 2015 (ES6), which allows defining a variable without the var
, const
, or let
keywords.with
statement: Although less common, some developers use the with
statement to create a scope for an expression.Keep in mind that these alternatives might not be as widely supported or optimized as the eval()
and new Function()
approaches.