var data = {};
for(var i = 0; i < 10000; i++)
{
data[`prop_${i}`] = true;
}
for(var i = 0; i < 10000; i++)
{
var propName = `prop_${i}`;
Object.assign(data, { [propName]: true });
}
Object.fromEntries(
Array(10000)
.fill(true)
.map((value, index) => [index, value]),
)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Direct Assignment 31312321321 | |
Object.assign 213123 | |
test direct assignment 123213 |
Test name | Executions per second |
---|---|
Direct Assignment 31312321321 | 239.0 Ops/sec |
Object.assign 213123 | 64.6 Ops/sec |
test direct assignment 123213 | 2295.9 Ops/sec |
Let's break down the provided JSON and explain what's being tested.
Benchmark Definition
The first part of the JSON represents a benchmark definition, which is a simple JavaScript script that creates an object with properties named "prop_0", "prop_1", ..., "prop_9999". The script does not actually create any data; it only sets up a structure for future assignments or operations.
Test Cases
The second part of the JSON contains three test cases, each representing a different approach to assigning values to an object:
for
loop to iterate 10,000 times and assign a value (true
) to each property of the data
object using dot notation (e.g., data['prop_0'] = true;
).Object.assign()
method to create an object with properties from an array. It iterates 10,000 times and creates an array of objects with a single property ({ [index]: true }
). The Object.assign()
method is then used to assign these objects to the data
object.Array.fromEntries()
method (available in modern JavaScript) to create an array of key-value pairs and then passes it to Object.fromEntries()
, which creates a new object from the array.Options Compared
The three test cases are designed to compare the performance of different approaches for assigning values to an object:
Object.assign()
function to assign properties to an object.Array.fromEntries()
and Object.fromEntries()
.Pros and Cons
Here are some pros and cons of each approach:
data[
prop_${i}] = true;
).Object.assign()
.Library or Special JS Feature
None of the test cases use a specific library or special JavaScript feature beyond the standard Object.assign()
method. However, the Array.fromEntries()
method is a modern JavaScript feature introduced in ECMAScript 2019.
Other Considerations
When running benchmarks like this, it's essential to consider factors such as:
Alternatives
Other alternatives to these approaches might include:
Keep in mind that the specific alternatives will depend on the requirements and constraints of your use case.