var func1 = new Function("d", "return Math.log(2, d)");
var func2 = (d) => Math.log(2, d);
let x = func1(200);
let x = func2(200)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
new Function | |
native fn |
Test name | Executions per second |
---|---|
new Function | 16058712.0 Ops/sec |
native fn | 6628096.5 Ops/sec |
Let's break down what's being tested in this benchmark.
Overview
The benchmark compares the performance of two approaches: creating a new function using the new Function()
constructor and defining a native function using an arrow function syntax ((d) => ...
). The test cases measure how many executions per second each approach can perform on a simple mathematical operation involving logarithms.
What's being tested
The benchmark tests the performance of two different ways to create a function:
new Function()
: This approach creates a new function using the Function
constructor. The syntax is: var func = new Function('param1', 'return expression')
.(param) => expression
). In this case, the test uses the simple (d) => Math.log(2, d)
syntax.Options compared
The benchmark compares two options:
new Function()
(Option 1): Creates a new function dynamically at runtime.Pros and Cons of each approach:
new Function()
new Function()
, as you're limited to defining functions with specific parameter names.Library and special JS feature
There is no library or special JS feature being used in this benchmark. It only relies on standard JavaScript features, such as the Function
constructor and arrow function syntax.
Alternative approaches
If you want to explore alternative approaches for creating functions in JavaScript:
new Function()
constructor, you can use a constructor function (e.g., class Func { ... }
) to create new functions dynamically.Keep in mind that these alternatives might have different performance characteristics compared to native function definition using arrow functions.