var array = (new Array(10000)).fill(0).map((x, i) => {
return {
value: i + 1,
name: `name ${i+1}`,
nameDealer: `nameDealer ${i+1}`
}
})
for (let accessory of array) {
console.log(accessory);
if (accessory.nameDealer) {
accessory.name = accessory.nameDealer;
}
}
array.forEach((item) => {
console.log(item);
if (item.nameDealer) {
item.name = item.nameDealer;
}
})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For in | |
For each |
Test name | Executions per second |
---|---|
For in | 24.2 Ops/sec |
For each | 24.3 Ops/sec |
I'd be happy to explain the benchmark and its different approaches.
Overview
The provided JSON represents a JavaScript microbenchmarking test case on MeasureThat.net. The test case measures the performance difference between two loops: for in
and forEach
. The goal is to update one value of each object in an array using these two loops.
Script Preparation Code
The script preparation code defines an array array
with 10,000 objects, each containing three properties: value
, name
, and nameDealer
. This array will be used as the test data.
Benchmark Definition
There are two benchmark definitions:
array
using a traditional for in
loop, logging each object and updating its name
property if it has a matching nameDealer
property.forEach
method to iterate over the array
, logging each object and updating its name
property if it has a matching nameDealer
property.Options Compared
The two loops offer different approaches:
for in
is a traditional loop with explicit iteration, while forEach
uses a callback function to iterate over the array.for each
might be more memory-efficient since it doesn't require creating an iterator object like for in
.for each
can be considered more readable because it's a standard JavaScript method, whereas for in
requires manual iteration.Pros and Cons
Library Usage
There is no explicit library usage in this benchmark. However, it's worth noting that both for in
and forEach
rely on JavaScript's built-in array methods.
Special JS Features or Syntax
None of the provided code uses special JavaScript features or syntax beyond what's standard for JavaScript development.
Other Alternatives
Other alternatives to for in
and forEach
include:
for in
and forEach
.In conclusion, the benchmark tests the performance difference between two common loop constructs in JavaScript: for in
and forEach
. The choice of loop depends on the desired trade-off between control, readability, and potential performance overhead.