<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[i] = 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 | 1233339.6 Ops/sec |
testArrayMap | 1648972.4 Ops/sec |
testUnderscoreMap | 1935855.0 Ops/sec |
testLodashMap | 1995094.4 Ops/sec |
testForLoop | 1265144.1 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark is designed to measure the performance of four different ways to extract the type
property from an array of objects: using Array.prototype.map()
, underscore.js
, lodash.js
, and a traditional for
loop.
Options Compared
_
): A JavaScript library that provides functional programming helpers, including map()
._
): Another popular JavaScript library that provides functional programming helpers, including map()
.for
loop: This method uses a manual for
loop to iterate over the array and extract the desired property.Pros and Cons of Each Approach
(
_`): Pros: Provides a simple and concise way to perform common functional programming tasks. Cons: Adds an external dependency (the underscore library) and may not be familiar to all developers. (
_`): Similar to Underscore.js, but with more features and options. Pros: Provides more functionality than Underscore.js, but also adds an extra dependency.for
loop:Library Descriptions
map()
, filter()
, and more.Other Considerations
Alternatives
If you don't want to use external libraries, you can also consider using other methods, such as:
Array.prototype.forEach()
instead of map()
However, these alternatives may have different performance characteristics and trade-offs compared to the approaches tested in this benchmark.