<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js'></script>
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
var arr = [];
for(var i = 0; i < 1000; i++){
arr.push({value:getRandomInt(100)});
}
_.max(arr);
Math.max(arr)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.max | |
Math.max |
Test name | Executions per second |
---|---|
_.max | 16178.9 Ops/sec |
Math.max | 20069.5 Ops/sec |
Let's break down what's being tested in this benchmark.
Overview
The benchmark is comparing the performance of two functions: _.max
from the Lodash library and Math.max
. The test creates an array of 1000 objects, each with a random value between 0 and 100. The purpose of this test is to measure which function is faster in executing.
Options compared
Two options are being compared:
Pros and Cons of each approach
Math.max
with arrays.Library: Lodash
Lodash is a popular JavaScript library that provides a set of functional programming helpers. The _max
function is one of its utility functions, which is used here to compare performance. By using Lodash, the test creates more readable code and may benefit from optimizations implemented in the library.
Special JS feature/syntax (none mentioned)
There are no special JavaScript features or syntaxes being tested in this benchmark. The code uses standard JavaScript features like arrays, loops, and functions.
Other alternatives
If you want to compare other options, here are a few examples:
Array.prototype.reduce()
: Instead of using Lodash's _max
function, you could use the reduce()
method on the array to find the maximum value.Array.prototype.every()
and Math.max()
: You could create a custom implementation that uses every()
to check if all elements in the array are less than or equal to the current max value, and then returns Math.max()
with the initial value of 0.These alternatives would require more code and may not be as optimized as the original comparison using Lodash's _max
function.