<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
var arr = [];
for (var i = 0; i < 100000; i++) {
arr.push({
value: getRandomInt(100)
});
}
_.sortBy(arr,"value");
const sortByKey = (array, key) => arr.sort((a,b) => a[key] > b[key]);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.sortBy | |
sortByKey |
Test name | Executions per second |
---|---|
_.sortBy | 3.4 Ops/sec |
sortByKey | 1195741824.0 Ops/sec |
I'll break down the provided benchmark definition and explain what's being tested, compared, and considered.
Benchmark Definition
The website MeasureThat.net allows users to create microbenchmarks by providing JavaScript code that represents a specific task or operation. The provided benchmark definition consists of:
Name
: A descriptive name for the benchmark.Description
: An optional description of the benchmark (not provided in this example).Script Preparation Code
: A JavaScript function that prepares the data needed for the benchmark. In this case, it generates an array with 100,000 objects, each containing a random value between 0 and 100.Html Preparation Code
: A snippet of HTML that includes a reference to the Lodash library (version 4.17.5), which provides functional programming utilities.Individual Test Cases
The benchmark defines two individual test cases:
**: This test case uses the
_.sortBy()` function from the Lodash library, which sorts an array in place based on a specified key.const sortByKey = (array, key) => arr.sort((a,b) => a[key] > b[key])
: This test case implements a custom sorting algorithm that sorts an array based on a specific key.Comparison of Approaches
The two approaches are compared in terms of their performance:
const sortByKey = (array, key) => arr.sort((a,b) => a[key] > b[key])
: Implements a custom sorting algorithm using the sort()
method and a compare function.Pros and Cons
const sortByKey = (array, key) => arr.sort((a,b) => a[key] > b[key])
:BigInt
for large numbers).Library: Lodash
The Lodash library provides a comprehensive set of functional programming utilities, including _.sortBy()
. This function is designed to perform stable sorts on arrays, ensuring that equal elements maintain their original order.
Special JS Features/Syntax (Not Applicable in this Example)
There are no special JavaScript features or syntax used in this benchmark. The code only utilizes standard ECMAScript syntax and libraries (Lodash).
Other Alternatives
For custom sorting algorithms like const sortByKey = (array, key) => arr.sort((a,b) => a[key] > b[key])
, other alternatives include:
Array.prototype.sort()
method with a custom compare function.Keep in mind that these alternatives may have different performance characteristics and trade-offs, depending on the specific use case and requirements.