<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var array = [];
var max = 10000;
for (let i = 1; i <= max; ++i) {
array.push(i);
}
_.reduce(array, (sum, number) => sum += number, 0);
array.reduce((sum, number) => sum += number, 0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash reduce | |
Native reduce |
Test name | Executions per second |
---|---|
Lodash reduce | 10130.2 Ops/sec |
Native reduce | 29518.6 Ops/sec |
Let's break down the benchmark and explain what is being tested.
Benchmark Overview
The benchmark compares two approaches to reduce an array of numbers: using the Lodash library's reduce
function and implementing a native JavaScript implementation of reduce
.
Script Preparation Code
The script preparation code generates an array of 10,000 random numbers and assigns it to the variable array
. This code is executed before running each benchmark test.
Html Preparation Code
The HTML preparation code includes a script tag that loads the Lodash library version 4.17.5 from a CDN. This ensures that the Lodash library is available for use in the benchmark tests.
Individual Test Cases
There are two individual test cases:
reduce
function with the following arguments:array
: the array to be reduced(sum, number) => sum += number, 0
: a callback function that takes two arguments: sum
(the accumulator) and number
(the current element being processed). The callback returns the updated sum
by adding number
.reduce
method with the same arguments as above.Comparison
The benchmark compares the execution performance of both approaches on a desktop device running Chrome 76 browser. The results are:
Test Name | Browser | Device Platform | Operating System | Executions Per Second |
---|---|---|---|---|
Native reduce | Chrome 76 | Desktop | Windows | 29518.626953125 |
Lodash reduce | Chrome 76 | Desktop | Windows | 10130.212890625 |
Pros and Cons
reduce
function.Library - Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks such as data manipulation, string manipulation, and more. The reduce
function is one of its core exports, providing a concise way to iterate over arrays and reduce them to a single value.
Special JS Feature - Closures
The callback function passed to both reduce
methods uses closures, which are functions that have access to their own scope and can capture variables from the surrounding context. In this case, the closure is used to accumulate the sum of numbers in the array.
Other alternatives to consider: