var data = new Array(1000000).fill(undefined).map((_,i) => i)
var obj = data.reduce((obj, idx) => {obj['idx' + Date.now()] = {name: 'Name: ' + Date.now(), age: idx}; return obj}, {});
var map = new Map(Object.entries(obj));
var copy = {obj}
var copy = new Map(map)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object spread | |
new Map |
Test name | Executions per second |
---|---|
Object spread | 6489.1 Ops/sec |
new Map | 45678.6 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
The provided benchmark compares two approaches for creating a copy of an object: Object spread
and new Map
. The test case uses a complex data structure to create an object with a large number of properties, which is then copied using both methods.
What are we testing?
We're testing the performance of two different approaches:
var copy = {...obj}
): This method creates a new object by spreading the properties of the original obj
object into a new object literal.var copy = new Map(map)
): This method creates a new Map object from the entries in the original map
object.Options compared
The two approaches are compared in terms of their execution time, which is measured as the number of executions per second.
Pros and Cons
Here's a brief overview of each approach:
var copy = {...obj}
):var copy = new Map(map)
):map
constructor also iterates over the entries, adding additional performance overhead.Library and Purpose
In this benchmark, two libraries are used:
The map()
function is used to create a new map from the entries in the original object. The fill()
method is used to create a large array of undefined values, which is then reduced and spread into the object.
Special JS feature or syntax
There are no special JavaScript features or syntax mentioned in this benchmark.
Other alternatives
If you're interested in exploring other approaches, here are some alternatives:
cloneDeep()
function: A popular utility library that provides a deep clone function for objects and arrays.Keep in mind that the choice of approach depends on your specific use case and requirements. Measuring performance is crucial to determine which approach best suits your needs.