What performance optimization technique is demonstrated in this code?
// Before optimization
function calculateTotal(items) {
return items.map(item => item.price * item.quantity)
.filter(price => price > 0)
.reduce((sum, price) => sum + price, 0);
}
// After optimization
function calculateTotal(items) {
let total = 0;
for (let i = 0; i < items.length; i++) {
const price = items[i].price * items[i].quantity;
if (price > 0) {
total += price;
}
}
return total;
}
The code demonstrates avoiding intermediate arrays (or array chaining optimization). The original version creates multiple intermediate arrays through chained array methods: map() creates a new array of calculated prices, filter() creates another array with filtered prices, and then reduce() processes that array into a total. Each of these steps creates a new array in memory, which is inefficient when we only need the final sum. The optimized version uses a simple loop that calculates the running total directly, avoiding the creation of any intermediate arrays. This reduces memory usage and eliminates the overhead of multiple array iterations, making it more efficient, especially for large arrays. This technique is particularly valuable when processing large datasets where the intermediate results aren't needed separately.