<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var data = Array(1000000).fill({
filtering: true,
mapping: 42
});
const aux = [];
_.map(data, el => {aux.push(el.filtering)});
const aux = [];
_.forEach(data, el => {aux.push(el.filtering)});
const aux = [];
for (let index = 0; index < data.length; index++) {
const el = data[index];
aux.push(el.filtering)
}
const aux = [];
data.map(el => {aux.push(el.filtering)})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash map | |
lodash forEach | |
native for | |
native map |
Test name | Executions per second |
---|---|
lodash map | 64.2 Ops/sec |
lodash forEach | 41.5 Ops/sec |
native for | 101.2 Ops/sec |
native map | 48.9 Ops/sec |
Let's break down the provided JSON data and explain what's being tested.
Benchmark Definition
The benchmark is comparing four approaches:
map
: This uses the lodash
library to perform an array transformation using the map
function.forEach
: This uses the lodash
library to iterate over an array using the forEach
function and push elements to a new array.for
loop: This uses a traditional for
loop to iterate over the array and push elements to a new array.map
function: This uses the built-in JavaScript map
function to perform an array transformation.Options Compared
Each option is compared in terms of execution speed, measured by the number of executions per second (ExecutionsPerSecond).
Pros and Cons
map
and forEach
: These use a library to simplify iteration over arrays. They are likely to be faster than native implementations because they avoid the overhead of manual loop management.for
loop: This is a traditional approach that requires manual loop management, which can lead to slower performance due to the overhead of incrementing indices and checking loop conditions.map
function: While this is built-in and optimized for performance, it may not be as efficient as using a library like Lodash, especially for large datasets.Library: Lodash
Lodash is a popular JavaScript utility library that provides various functions for tasks such as array manipulation, string manipulation, and object manipulation. In this benchmark, lodash
is used to provide the map
and forEach
functions, which simplify iteration over arrays.
Special JS Feature/Syntax
None of the test cases use special JavaScript features or syntax.
Other Alternatives
If you need to iterate over an array in JavaScript, you can also use other approaches such as:
for
loop with a variable declared using the let
keyword.reduce()
: This function reduces an array by applying a function to each element and returns the accumulated value.However, these alternatives may not be as straightforward to implement as the options compared in this benchmark.