<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/6.6.1/math.min.js"></script>
var func = new Function("return 2 * 3");
eval("2 * 3");
func();
math.evaluate("2 * 3");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
eval | |
new Function | |
mathjs |
Test name | Executions per second |
---|---|
eval | 4912521.0 Ops/sec |
new Function | 138686672.0 Ops/sec |
mathjs | 680946.4 Ops/sec |
I'll break down the provided benchmark for you.
Benchmark Overview
The test compares three different approaches to execute arithmetic expressions:
eval
Function
constructorevaluate
methodOptions Comparison
Here are the pros and cons of each approach:
eval
Function
constructoreval
, as it doesn't execute arbitrary code.eval
in terms of execution speed.evaluate
methodeval
, as it uses a dedicated expression evaluation engine.Library and Special JS Features
The test case using Math.js library's evaluate
method includes the following:
Other Alternatives
If you're looking for alternative approaches to execute arithmetic expressions, consider:
*
(multiplication), /
(division), etc., which are generally faster and more efficient than the tested approaches.esprima
, recast
, or astringify
can be used instead of Math.js library.Keep in mind that these alternatives might require more expertise and setup compared to using a dedicated expression evaluation library like Math.js.