const jsArray = Array.from({ length: 1000 }, (_, i) => ({
id: i,
a: 1,
b: 2,
timeMs: 0,
}));
// * update jsArray timeMs with 1
jsArray.forEach((item) => (item.timeMs = 1));
const jsArray = Array.from({ length: 1000 }, (_, i) => ({
id: i,
a: 1,
b: 2,
timeMs: 0,
}));
// * update jsArray timeMs with jsArray.map
const jsArrayMap = jsArray.map((item) => ({ item, timeMs: 1 }));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JS Array set | |
JS Array map |
Test name | Executions per second |
---|---|
JS Array set | 32848.7 Ops/sec |
JS Array map | 23870.4 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
What is being tested?
MeasureThat.net is testing two different approaches for updating an array in JavaScript: using the forEach
method and using the map
method. The benchmark compares the performance of these two approaches on a large array with 1000 elements.
Options compared
There are two options being compared:
Pros and Cons
Library and purpose
In this benchmark, no specific library is used. The benchmark focuses on native JavaScript methods.
Special JS feature or syntax
There are no special JavaScript features or syntax being tested in this benchmark. However, it's worth noting that the map
method uses a more modern, concise syntax, which may be considered a minor optimization by some developers.
Other alternatives
Other approaches for updating an array could include:
for (var i = 0; i < arr.length; i++) { arr[i].timeMs = 1 }
)reduce
method to update each element individuallyKeep in mind that these alternatives may have different performance characteristics compared to the forEach
and map
methods.
Benchmark preparation code
The benchmark preparation code is minimal, as it only initializes an array of 1000 elements using Array.from
. The forEach
and map
tests then update this array by setting a specific property (timeMs
) to 1.