const source = {};
for( let i = 0; i < 10000; i++ ) {
source[ i ] = 'Lorem ipsum dolor nabet';
}
const target = {};
Object.assign( target, source );
const source = {};
for( let i = 0; i < 10000; i++ ) {
source[ i ] = 'Lorem ipsum dolor nabet';
}
const target = {};
Object.keys( source ).forEach( key => {
target[ key ] = source[ key ];
} );
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.assign | |
Copy object keys |
Test name | Executions per second |
---|---|
Object.assign | 913.6 Ops/sec |
Copy object keys | 4068.0 Ops/sec |
Let's dive into the Benchmark Definition and explain what's being tested.
The benchmark is comparing two approaches for copying large objects:
Object.assign()
: This method takes an object as an argument and assigns all own enumerable properties of another object to the target object, returning the original object. In this benchmark, Object.assign()
is used to copy 10,000 key-value pairs from a source object (source
) to a target object (target
).Object.keys()
method to get an array of the source object's property names, and then iterates over this array using forEach()
, assigning each property value to the corresponding key in the target object.Now, let's discuss the pros and cons of these approaches:
Object.assign()
Pros:
Cons:
Copying object keys manually
Pros:
Cons:
In general, Object.assign()
is a good choice when you need to copy objects with simple prototype chains and don't mind the extra method call overhead. However, if you're dealing with complex objects or custom prototypes, the manual copying approach might be more suitable.
Now, let's talk about the library used in this benchmark:
There are no libraries explicitly mentioned in the Benchmark Definition JSON. The Object.assign()
method is a built-in JavaScript method, and the manual copying approach uses only native JavaScript methods (Object.keys()
, forEach()
) without any external dependencies.
The test case doesn't use any special JavaScript features or syntax. However, if you're interested in exploring other benchmarking techniques or optimizing your code for performance, there are various libraries and tools available that can help, such as:
benchmark.js
or fast bench