var func = new Function("return 2 * 3");
function func2() { return 2 * 3 }
eval("2 * 3");
func();
func2()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
eval | |
new Function | |
regular function |
Test name | Executions per second |
---|---|
eval | 2594463.2 Ops/sec |
new Function | 15691530.0 Ops/sec |
regular function | 15406678.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
The provided JSON represents a benchmark test case that compares three different approaches for executing simple arithmetic expressions: eval
, new Function
, and regular functions.
What is tested?
In this benchmark, we're testing the execution speed of three different ways to evaluate a simple expression: 2 * 3
. The three approaches are:
eval
: The eval()
function executes a string as JavaScript code.new Function
: This approach creates a new anonymous function using the Function
constructor, and then invokes it with the desired arguments.function
keyword, and then calling that function.Options compared
The benchmark compares these three approaches in terms of their execution speed (measured in executions per second).
Pros and Cons:
eval
: Pros: Easy to use, doesn't require explicit function definition. Cons: Slow performance due to parsing and interpretation overhead.new Function
: Pros: Fast performance due to native code generation. Cons: Requires a bit more boilerplate code compared to regular functions.eval
, but still efficient.Library usage
In this benchmark, the Function
constructor is used to create an anonymous function. The purpose of Function
is to allow dynamic creation of functions without declaring a named function.
Special JavaScript features/syntax
This benchmark does not use any special JavaScript features or syntax beyond what's required for the test cases. If it did, I'd be happy to explain those in more detail!
Other alternatives
If you were to create a similar benchmark, you might consider additional approaches like:
Function expression
: A shorthand way of creating functions using arrow functions (e.g., (x) => x * 2
) or function expressions without the function
keyword (e.g., let func = (x) => x * 2;
).Native Web Workers
: Using web workers to offload computation from the main thread, which can significantly improve performance for CPU-intensive tasks.Keep in mind that these alternatives might be overkill for a simple arithmetic expression benchmark like this one.