var input = { foo: 'lorem', bar: null }
const { foo, bar } = input;
const result = {};
if (foo) {
result['foo'] = foo;
}
if (bar) {
result['bar'] = bar;
}
const { foo, bar } = input;
const result = {};
Object.assign(
foo ? { foo } : {},
bar ? { bar } : {}
);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Key assign | |
Object.assign |
Test name | Executions per second |
---|---|
Key assign | 10100566.0 Ops/sec |
Object.assign | 3280371.8 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Overview
The benchmark compares two approaches for assigning properties to an object: using key assignment (const { foo, bar } = input; const result = {}; if (foo) { result['foo'] = foo; } if (bar) { result['bar'] = bar; };
) and using Object.assign()
.
Options Compared
The two options are:
input
object and then assigning them to a new object (result
). This approach uses explicit property assignments.{ foo }
or { bar }
) to Object.assign()
to merge it with an empty object.Pros and Cons
foo
and bar
) before assigning them.Library
There is no external library mentioned in the benchmark definition. However, Object.assign()
is a built-in JavaScript method that comes with the language.
Special JS Feature/Syntax
None of the provided test cases use any special JavaScript features or syntax beyond what's considered standard (ECMAScript 2020).
Other Alternatives
For this specific benchmark, the alternative approaches would be:
Object.assign()
in a different way:const { foo, bar } = input;
const result = {};
result.foo = foo;
result.bar = bar;
Object.assign()
.assign
method for object merging.In summary, the benchmark is testing two approaches for assigning properties to an object: key assignment and Object.assign()
. The choice between these options depends on readability, performance, and code complexity.