const a = { a: 1, b: 2 };
const b = { b: 3, c: 4 };
const s = new Set([
Object.keys(a),
Object.keys(b),
]);
const res = Array.from(s);
const c = { a, b };
const res = Object.keys(c);
const s = new Set();
for(const x in a) s.add(x);
for(const x in b) s.add(x);
const res = Array.from(s);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set | |
Merge | |
For |
Test name | Executions per second |
---|---|
Set | 761872.1 Ops/sec |
Merge | 1730753.9 Ops/sec |
For | 1196404.5 Ops/sec |
The benchmark titled "Merge+object.keys vs set vs for" evaluates three different methods for merging the keys from two JavaScript objects (a
and b
), specifically looking at how efficiently they can consolidate the unique keys. The benchmark compares the following approaches:
Set
object combined with the spread operator to collect keys.for...in
loops to iterate over the objects and gather unique keys into a Set
.Set:
const s = new Set([...Object.keys(a), ...Object.keys(b)]);
const res = Array.from(s);
Set
, ensuring that each key is unique....
) provides a concise way to combine arrays.Array.from
.Merge:
const c = { ...a, ...b };
const res = Object.keys(c);
Object.keys
produces a straightforward array of keys representing the merged object.a
and b
have large numbers of keys, this can lead to more memory usage since a new object is created.For:
const s = new Set();
for (const x in a) s.add(x);
for (const x in b) s.add(x);
const res = Array.from(s);
for...in
can inadvertently include properties from the prototype chain unless safeguards are put in place (like checking hasOwnProperty
).The benchmarking showed the following performance results (executions per second):
Set
.Other alternatives to the methods evaluated can include:
Array.prototype.filter
combined with concat
to filter out the unique keys which can be slower than the object spread:const res = [...Object.keys(a).concat(Object.keys(b))]
.filter((value, index, self) => self.indexOf(value) === index);
_.uniq
and _.merge
:const res = _.uniq([...Object.keys(a), ...Object.keys(b)]);
These alternatives may offer different trade-offs in terms of readability, performance, and memory usage depending on the specific context of their implementation.