<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var generateText = function(){
return Math.random().toString(36).substring(2, 4);
}
var arr = []
for(i=0; i<100; i++){
const obj = {}
obj.id = i;
obj.text = generateText()
arr.push(obj)
}
_.orderBy(arr, ['text', 'id'], ['desc', 'asc'])
arr.sort((a, b) => (a.text < b.text) ? 1 : (a.text === b.text) ? ((a.id > b.id) ? 1 : -1) : -1 )
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.orderBy | |
Array.sort |
Test name | Executions per second |
---|---|
_.orderBy | 22169.0 Ops/sec |
Array.sort | 342042.1 Ops/sec |
Let's break down what's being tested in this benchmark.
What is being compared?
The benchmark compares two different approaches to sorting an array of objects:
Array.sort()
method with a custom comparison function._orderBy
function from the Lodash library (version 4.17.5).What are we sorting?
We're sorting an array of objects, where each object has two properties: id
and text
. The benchmark is specifically sorting this array in descending order by text
and ascending order by id
.
The options compared:
a
and b
) as input. The function returns a value that determines the sort order:a.text < b.text
, return 1 (descending order).a.text === b.text
, compare the id
values: if a.id > b.id
, return 1 (ascending order), otherwise return -1.['text', 'id']
), and a list of sort orders (['desc', 'asc']
) as input. It returns the sorted array.Pros/Cons:
Here are some general pros and cons of each approach:
Other considerations:
When deciding which approach to use, consider factors like:
Library and its purpose:
The Lodash library (version 4.17.5) provides utility functions for JavaScript development. In this case, the _orderBy
function simplifies the process of sorting arrays by multiple properties with custom orders.
JS feature or syntax used:
None specific to this benchmark are mentioned.
Alternatives:
If you don't want to use Lodash, alternative approaches to sorting arrays could be:
Hope this explanation helps!