const f1 = (a, b) => a.concat(b.map(String));
const f2 = (a, b) => a.concat(b.map(String));
const r1 = f1([0], 1, 2, 3, 4, 5);
const r2 = f2([0], [1, 2, 3, 4, 5]);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Rest | |
Array |
Test name | Executions per second |
---|---|
Rest | 13407240.0 Ops/sec |
Array | 13731010.0 Ops/sec |
This benchmark compares the performance of two different ways to handle function parameters in JavaScript: using rest parameters and using array parameters.
Rest Parameters (f1
): This syntax allows a function to accept an indefinite number of arguments as an array. In the benchmark, f1
is defined as:
const f1 = (a, ...b) => a.concat(b.map(String));
Here, a
is the first argument, and b
is an array containing the rest of the arguments passed to the function.
Array Parameters (f2
): This approach uses a traditional method of passing an array as one of the parameters. In the benchmark, f2
is defined as:
const f2 = (a, b) => a.concat(b.map(String));
Here, a
is a single argument, and b
is also expected to be an array.
Rest Parameters:
Array Parameters:
f2
) executed roughly 13,731,010 times per second, while the rest parameter approach (f1
) executed about 13,407,240 times per second. This indicates that in this specific benchmarking setup, the array parameter approach was marginally faster.Apart from rest and array parameters, JavaScript developers may consider:
function myFunc(a, b, c) {}
), which can lead to clearer code when the number of arguments is known, but lacks flexibility.function myFunc({ a, b, c }) {}
) can enhance readability and avoid parameter order issues, but introduces some overhead in creating the object.arguments
object (applicable in non-arrow functions), though this method has been discouraged in modern JavaScript due to its inherent limitations and lack of clarity.In summary, selecting between rest and array parameters depends on the specific use case, and developers should consider both performance and code clarity when making their decision.