<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script>
underscore = _;
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.12.0/lodash.min.js"></script>
<script>
lodash = _;
</script>
</head>
<body>
</body>
</html>
var PromosArray = [
{
type: "regular",
display: "$123.00"
},
{
type: "markdown",
display: "$100.00"
},
{
type: "promo",
display: "$80.00"
}
];
function testArrayIteration() {
var items = [];
var i;
for (i = 0; i < PromosArray.length; i++) {
items.push(PromosArray[i].type);
}
return items;
}
function testArrayMap() {
return PromosArray.map(function (promo) {
return promo.type;
});
}
function testUnderscoreMap() {
return underscore.map(PromosArray, function (promo) {
return promo.type;
});
}
function testLodashMap() {
return lodash.map(PromosArray, function (promo) {
return promo.type;
});
}
function testForLoop() {
var newArray = [];
for (var i = 0; i < PromosArray.length; i++) {
newArray.push(PromosArray[i].type);
}
return newArray;
}
testArrayIteration();
testArrayMap();
testUnderscoreMap();
testLodashMap();
testForLoop();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
testArrayIteration | |
testArrayMap | |
testUnderscoreMap | |
testLodashMap | |
testForLoop |
Test name | Executions per second |
---|---|
testArrayIteration | 1290710.0 Ops/sec |
testArrayMap | 1702379.6 Ops/sec |
testUnderscoreMap | 2092334.5 Ops/sec |
testLodashMap | 2214293.8 Ops/sec |
testForLoop | 1288239.0 Ops/sec |
Measuring the performance of different JavaScript array iteration methods is an essential task in understanding how to optimize code for various use cases.
Benchmark Overview
The provided benchmark measures the execution time of four different ways to iterate over an array:
Each test case involves iterating over a predefined array (PromosArray
) and extracting the type
property of each object.
Options Compared:
Pros:
Cons:
_.map()
is part of the popular Underscore.js library.Array.prototype.map()
, but as a function outside the array context.Pros:
.map()
method with utility functionsCons:
_.map()
is another popular function from the Lodash library..map()
method with utility functions.Pros:
Cons:
Pros:
Cons:
.map()
methods or those provided by utility libraries