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 });
}
data = Object.fromEntries(
Array(10000)
.fill(true)
.map((value, index) => [index, value]),
)
Object.assign(data, Object.fromEntries(
Array(10000)
.fill(true)
.map((value, index) => [index, value]),
))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Direct Assignment | |
Object.assign | |
test direct assignment | |
test direct assignment second approach |
Test name | Executions per second |
---|---|
Direct Assignment | 884.6 Ops/sec |
Object.assign | 171.5 Ops/sec |
test direct assignment | 5293.6 Ops/sec |
test direct assignment second approach | 767.6 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Overview
The benchmark compares three different approaches for assigning values to an object:
Object.assign
Object.fromEntries
We'll explore each approach, their pros and cons, and other considerations.
Direct Assignment
Direct assignment involves creating a property on the object using the dot notation (data[
prop_] = true;
) for each iteration of the loop. This is a simple and straightforward way to assign values to an object.
Pros:
Cons:
Object.assign
Object.assign
is a method that copies the specified values from one or more source objects to a target object. In this benchmark, it's used to assign an array of properties to the data
object.
Pros:
Cons:
Object.assign
with an array of properties)Object.fromEntries
Object.fromEntries
is a method that creates a new object from the specified key-value pairs. In this benchmark, it's used as an alternative way to assign values to the data
object.
Pros:
Cons:
Library and Special JS Features
None of these approaches rely on any specific libraries or special JavaScript features. They are all standard language constructs.
However, it's worth noting that the benchmark uses a technique called "property iteration" to generate an array of properties for assignment. This is a common pattern in JavaScript benchmarks and can affect performance.
Other Alternatives
In addition to these three approaches, there may be other ways to assign values to an object, such as using Array.prototype.forEach
or creating a custom loop. However, these alternatives are not included in this benchmark.
Overall, the benchmark provides a good comparison of three different approaches for assigning values to an object, highlighting the trade-offs between direct assignment, Object.assign
, and Object.fromEntries
.