<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var array = [
{ 'name': 'lim', 'age': 26 },
{ 'name': 'kim', 'age': 28 },
{ 'name': 'choi', 'age': 32 },
{ 'name': 'park', 'age': 21 }
];
var result = _.reduce(array, (prev, cur) => {
return prev + cur.age;
}, 0);
var result = array.reduce((prev, cur) => {
return prev + cur.age;
}, 0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash reduce method | |
es6 reduce method |
Test name | Executions per second |
---|---|
lodash reduce method | 6325768.5 Ops/sec |
es6 reduce method | 16436991.0 Ops/sec |
Benchmark Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The provided benchmark compares the performance of the reduce
method from two different approaches: Lodash (a popular utility library for JavaScript) and the built-in Array.prototype.reduce()
method in ES6 (EcmaScript 2015).
Test Cases
There are two individual test cases:
_.reduce()
function from Lodash, which is used to reduce an array to a single value.var result = _.reduce(array, (prev, cur) => {\r\n return prev + cur.age;\r\n}, 0);
Array.prototype.reduce()
method in ES6, which is used to reduce an array to a single value.var result = array.reduce((prev, cur) => {\r\n return prev + cur.age;\r\n}, 0);
Options Compared
The two approaches are compared in terms of their performance. The benchmark measures the number of executions per second for each method.
Pros and Cons
Library: Lodash
Lodash is a popular utility library for JavaScript that provides a wide range of functions for common tasks such as array manipulation, string processing, and object transformation. The _.reduce()
function is part of this library and provides a convenient way to reduce arrays to single values.
Special JS Feature/Syntax
There are no special JavaScript features or syntax used in these test cases.
Other Considerations
_.reduce()
function may be slower due to the overhead of a library call, while the built-in ES6 method may be faster but requires more manual effort from developers.Alternatives
Other alternatives for array reduction in JavaScript include:
forEach()
method to iterate over the array and calculate the result manually.These alternatives may offer different trade-offs in terms of performance, readability, and maintainability, depending on the specific use case and requirements.