<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");
arr.sort((a,b) => a.value > b.value);
arr.sort((a,b) => (a.value > b.value) ? 1 : (a.value < b.value) ? -1 : 0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.sortBy | |
sortByKey | |
sortByKeyOriginal |
Test name | Executions per second |
---|---|
_.sortBy | 3.8 Ops/sec |
sortByKey | 56.2 Ops/sec |
sortByKeyOriginal | 58.3 Ops/sec |
I'll break down the provided benchmark definition and explain what's being tested, compared, and some pros/cons of each approach.
Benchmark Definition
The benchmark measures the performance of sorting an array of objects using three different methods:
_.sortBy(arr, "value")
: Uses the Lodash library to perform a stable sort on the array based on the value property of each object.arr.sort((a, b) => a.value > b.value)
: Performs a custom comparison function-based sort on the array.arr.sort((a, b) => (a.value > b.value) ? 1 : (a.value < b.value) ? -1 : 0)
: Similar to the second approach, but uses a more explicit comparison function.Options Compared
The benchmark compares three sorting algorithms:
sortBy
method: A popular library for functional programming tasks, providing a concise and efficient way to sort arrays.Pros/Cons of each approach
sortBy
method:Library - Lodash
Lodash is a popular utility library for JavaScript that provides a wide range of functions for tasks like array manipulation, object transformation, and more. The sortBy
function in this benchmark uses Lodash's implementation of stable sorting, which ensures that equal elements remain in their original order during the sorting process.
Special JS Feature - Arrow Functions
The custom comparison function-based sort uses arrow functions ((a, b) => a.value > b.value
) to define the comparison logic. Arrow functions are a concise way to define small, single-expression functions in JavaScript and provide several benefits, including:
function
keywords and return statements.this
keyword or additional binding.Overall, this benchmark provides valuable insights into the performance differences between three distinct sorting algorithms, allowing developers to choose the most suitable approach based on their specific requirements and constraints.