var first = {
foo: "string",
bar: 42,
baz: 100.56,
quux: "another string",
foobar: {
one: "foo bar",
two: "bar foo"
},
bazbaz: function (a, b) {
return a * a % b + 100 / b;
}
};
var second = {
one: "x",
two: "y",
three: "z",
x: "one",
y: "two",
z: "three",
foo: "string 2",
bar: 43
};
const third_assign = Object.assign({}, first, second);
return third_assign;
const third_spread = {
first,
second,
};
return third_spread;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object assign | |
Object spread |
Test name | Executions per second |
---|---|
Object assign | 772325.4 Ops/sec |
Object spread | 92813.4 Ops/sec |
Benchmark Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks, comparing different approaches to achieve the same goal. In this case, we have two test cases: "Object assign" and "Object spread". The benchmark measures which approach is faster, using a specific dataset provided in the Benchmark Definition JSON.
Benchmark Definition JSON
The Benchmark Definition JSON contains information about the script preparation code, which defines an object first
with various properties, including nested objects and functions. This object will be used to test two different approaches: object assignment (Object.assign
) and object spread (...
).
The Script Preparation Code is:
var first = {
foo: "string",
bar: 42,
baz: 100.56,
quux: "another string",
foobar: {
one: "foo bar",
two: "bar foo"
},
bazbaz: function (a, b) {
return a * a % b + 100 / b;
}
};
var second = {
one: "x",
two: "y",
three: "z",
x: "one",
y: "two",
z: "three",
foo: "string 2",
bar: 43
};
Options Compared
Two options are compared:
Object.assign
): This approach uses the Object.assign()
method to merge two objects into a new object.const third_assign = Object.assign({}, first, second);
return third_assign;
...
): This approach uses the spread operator (...
) to create a new object with properties from both first
and second
.const third_spread = {
...first,
...second,
};
return third_spread;
Pros and Cons
Object assignment (Object.assign
)
Pros:
Cons:
Object spread (...
)
Pros:
Cons:
Library and Special JS Feature
There is no specific library used in this benchmark, but it does use the spread operator (...
), which is a modern JavaScript feature introduced in ECMAScript 2018.
Other Considerations
Alternatives
Other alternatives to these approaches could include:
However, these alternatives may not be relevant to this specific benchmark, which focuses on comparing two basic approaches to merging objects: object assignment and object spread.