<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/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)});
}
Math.max(arr)
_.max(arr)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Native js Math.max | |
Lodash max |
Test name | Executions per second |
---|---|
Native js Math.max | 46681.9 Ops/sec |
Lodash max | 15659.7 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Definition
The benchmark is comparing two approaches to find the maximum value in an array: using JavaScript's built-in Math.max()
function versus using the popular utility library Lodash's _.max()
function.
Script Preparation Code
The script preparation code generates a random array of 1000 objects, each with a random integer value between 1 and 100. This is done to create a large dataset that can be used to measure performance.
Html Preparation Code
The HTML preparation code includes a script tag that loads the Lodash library from a CDN. This allows us to test both native JavaScript's Math.max()
function and the Lodash version in the same benchmark.
Individual Test Cases
There are two individual test cases:
Math.max()
function._.max()
function.Pros and Cons:
Math.max()
.Library: Lodash
Lodash is a popular utility library for JavaScript that provides a wide range of functions for tasks like array manipulation, object manipulation, and more. In this benchmark, it's used for its _.max()
function, which implements a efficient algorithm for finding the maximum value in an array.
Special JS Feature/Syntax: None
There are no special JavaScript features or syntax being tested in this benchmark.
Other Alternatives:
If you wanted to test alternative approaches, you could consider using other libraries like:
: An older approach that uses
Math.max()with the
apply()` method to apply it to an array.Keep in mind that these alternatives might have different performance characteristics, so they'd need to be tested separately.