var arr = [];
for (var i = 0; i < 1000; i++) {
arr[i] = {
name: `${i}`,
value: i
};
}
function someFn(i) {
const x24 = i.value * 3 * 8;
i.value = x24;
i.name = `${x24}`;
return i;
}
for (var y of arr) {
someFn(y);
}
arr.map(item => someFn(item))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for of | |
map |
Test name | Executions per second |
---|---|
for of | 34940.9 Ops/sec |
map | 34092.4 Ops/sec |
Let's break down the provided benchmark and its results.
Benchmark Overview
The mutate-vs-map
benchmark compares two approaches to modify an array: using a for...of
loop and using the map()
method.
Script Preparation Code
The script preparation code creates an empty array arr
with 1000 elements, each containing name
and value
properties. The someFn
function is defined to take an object i
as an argument, modify its value
property by multiplying it by 3 and 8, update the name
property with the result, and return the modified object.
Html Preparation Code
There is no HTML preparation code provided, which suggests that this benchmark only runs in a headless browser or doesn't require any specific HTML setup.
Individual Test Cases
The two test cases are:
for of
: This test case uses a for...of
loop to iterate over the array and calls the someFn
function on each element.map
: This test case uses the map()
method to create a new array with the modified elements.Benchmark Results
The latest benchmark results show two browsers (Firefox 119) running on different platforms:
for of
: 34940.9375 executions per secondmap
: 34092.4296875 executions per secondOptions Compared
The two options being compared are:
for...of
loop to iterate over the array and call a function on each element.map()
method to create a new array with modified elements.Pros and Cons of Each Approach
map()
.map()
.Library
The map()
method uses the Array.prototype.map() method, which is a built-in JavaScript method. The purpose of this method is to create a new array with the results of applying a provided function on every element in an existing array.
Special JS Feature/Syntax
There is no special JavaScript feature or syntax used in this benchmark that would affect its execution or behavior.
Alternatives
Some alternative approaches to modifying arrays include:
forEach()
: While not as efficient as map()
for large arrays, forEach()
can be a suitable option when working with small arrays or older browsers.reduce()
: This method can be used to create a new array by reducing the original array to a single value. However, it may not be as efficient as map()
and requires more complex logic to achieve the desired result.Keep in mind that the best approach depends on the specific requirements of your use case, such as performance, memory usage, or data structure preservation.