<!--your preparation HTML code goes here-->
const data = {};
for (let i = 0; i < 10000; i++) {
data[i] = {
data: String.fromCharCode(97 + i),
value: Math.floor(Math.random() * 100),
isActive: Math.random() > 0.5
};
}
const allValues = Object.values(data);
allValues.forEach((num) => {
console.log(num.data);
});
for (const key in data) {
const value = data[key];
console.log(value.data);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
obj.values foreach | |
for const |
Test name | Executions per second |
---|---|
obj.values foreach | 47.2 Ops/sec |
for const | 48.3 Ops/sec |
This benchmark compares two different JavaScript approaches to iterate over object properties: using Object.values()
with forEach
, and a traditional for...in
loop.
Test Case 1: obj.values foreach
const allValues = Object.values(data);
allValues.forEach((num) => {
console.log(num.data);
});
data
into an array of its values using Object.values(data)
, which returns an array of the values present in the object.Array.prototype.forEach()
method to iterate over these values and log the data
property of each value object.forEach
method is specifically an array method and is designed for iteration.Test Case 2: for const
for (const key in data) {
const value = data[key];
console.log(value.data);
}
for...in
loop to iterate directly over the keys in the object data
.data
property.for...in
loop iterates over all properties, including inherited ones, which could introduce bugs if not careful (though for...in
can be coupled with hasOwnProperty
to mitigate this).According to the benchmark results:
for const
test recorded 48.33 executions per second.obj.values foreach
test recorded 47.22 executions per second.In conclusion, this benchmark illustrates that while the for...in
loop is slightly faster in this specific test case, both methods are acceptable depending on the situation.
for...of
Loop: This can be used with arrays but not directly with objects. You may need to convert objects to arrays first, which introduces similar overhead as Object.values()
.map
Method: For cases where you want to transform data while iterating, map()
can be useful, but also introduces the need for array creation.for
Loop: A standard for
loop can iterate over an array of values if you've converted the object to an array format. This combines some of the flexibility and control of both methods.Ultimately, which approach to choose may depend on the specific context of the application, the size of the data set, and performance requirements.