var params = { b:"hello", c: true, d:7 };
var other = Object.assign({ a: 2 }, params);
var params = { b:"hello", c: true, d:7 };
var other = { a: 2, params };
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.assign | |
spread operator |
Test name | Executions per second |
---|---|
Object.assign | 4802539.5 Ops/sec |
spread operator | 2007976.4 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks and explain what's being tested on MeasureThat.net.
Benchmark Definition
The benchmark is comparing two approaches to merge objects in JavaScript:
Object.assign()
: This method takes multiple source objects and merges them into a single target object....
): This operator allows you to create a new object by spreading the properties of an existing object.Options being compared
The benchmark is comparing the performance of these two approaches on a simple test case where we have an object params
with four properties (b, c, d) and another object with one property (a). We then attempt to merge these two objects using Object.assign()
or the spread operator.
Pros and Cons
Object.assign()
:...
):Library and special JS feature
There is no specific library used in this benchmark. However, the use of the spread operator (...
) relies on a feature introduced in ECMAScript 2018 (ES9).
Other alternatives
Before the spread operator became widely supported, other methods were used to merge objects, such as:
for...in
loop: Used params
object's property names and assigned them to the target object.Object.keys()
, Array.prototype.forEach()
: Used Object.keys(params)
to get an array of property names and then iterated over it using forEach()
to assign properties to the target object.Benchmark preparation code
The benchmark preparation code is empty, which means that the test cases use a minimal setup. The HTML preparation code is also empty, indicating that no specific HTML setup is required for this benchmark.
In summary, this benchmark tests the performance of two approaches to merge objects in JavaScript: Object.assign()
and the spread operator (...
). The spread operator is generally faster but requires JavaScript 2.6 or later.