var data = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: 6,
g: 7
}
function f1(a, b, c, d, e, f, g) {
return a + b + c + d + e + f + g;
}
function f2({
a,
b,
c,
d,
e,
f,
g
}) {
return a + b + c + d + e + f + g;
}
f1(data.a, data.b, data.c, data.d, data.e, data.f, Math.random())
data.g = Math.random();
f2(data)
f2({ data, g: Math.random() })
f2({ a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: Math.random() })
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Multiple parameters | |
Existing parameter object | |
Parameter object with spreading | |
New parameter object |
Test name | Executions per second |
---|---|
Multiple parameters | 3902959.0 Ops/sec |
Existing parameter object | 6951874.0 Ops/sec |
Parameter object with spreading | 7182855.5 Ops/sec |
New parameter object | 11536934.0 Ops/sec |
The provided JSON represents a JavaScript benchmark test case on the MeasureThat.net website. The test compares the execution performance of two functions, f1
and f2
, which are designed to calculate the sum of multiple parameters.
Function f1
Function f1
takes seven separate arguments: a
, b
, c
, d
, e
, f
, and g
. The function returns their sum.
function f1(a, b, c, d, e, f, g) {
return a + b + c + d + e + f + g;
}
Function f2
Function f2
takes an object with six properties: a
, b
, c
, d
, e
, and f
. The function returns the sum of these properties.
function f2({ a, b, c, d, e, f }) {
return a + b + c + d + e + f;
}
Options being compared
The benchmark test compares four different scenarios:
f1
): Calling f1
with seven separate arguments.f2
): Passing an existing object data
to f2
.f2
): Creating a new object by spreading data
and adding a new property g
.f2
): Passing a new object with all six properties explicitly set.Pros and cons of each approach
f1
):f2
):data
object being available.f2
):f2
):Library usage
Function f1
does not use any libraries explicitly, but it relies on the JavaScript language itself for execution.
Functions f2
, however, implicitly rely on the Object
type and its methods (e.g., { a, b, c, d, e, f }
). The spread operator ({ ...data, g: Math.random() }
) used in the "Parameter object with spreading" test case is also part of the JavaScript language.
Special JS feature or syntax
The benchmark uses the Math.random()
function to generate a random value for some tests. This is a built-in JavaScript function that returns a pseudo-random number between 0 (inclusive) and 1 (exclusive).
Overall, this benchmark provides a fair comparison of different approaches to passing parameters to functions in JavaScript, highlighting the trade-offs between simplicity, efficiency, and explicitness.