<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.js"></script>
var users = [
{ 'user': 'joey', 'age': 32 },
{ 'user': 'ross', 'age': 41 },
{ 'user': 'chandler', 'age': 39 }
]
users.sort((a,b) => a.user.localeCompare(b.user));
_.sortBy(users, 'user', 'asc')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
native sort of objects by localeCompare | |
lodash _.orderBy |
Test name | Executions per second |
---|---|
native sort of objects by localeCompare | 7206919.0 Ops/sec |
lodash _.orderBy | 3392366.8 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Overview
The provided JSON represents a benchmark test on MeasureThat.net, which compares the performance of two approaches for sorting objects by localeCompare: native sort using localeCompare
and lodash _.sortBy
. The benchmark also includes a second test case that uses lodash _.orderBy
, but this will be discussed separately.
Options Compared
The two options compared in this benchmark are:
localeCompare
: This approach uses the built-in localeCompare
method to compare strings.sortBy
function to sort objects.Pros and Cons of Each Approach
localeCompare
Pros:
Cons:
Pros:
Cons:
Library: Lodash
Lodash is a popular JavaScript library that provides a wide range of utility functions for tasks like sorting, mapping, and more. The sortBy
function takes three arguments: an array of objects to be sorted, a key function, and a sorting order (in this case, ascending).
Special JS Feature/ Syntax: localeCompare
The localeCompare
method is a built-in JavaScript function that compares two strings according to the Unicode Standard for comparing strings. It's used here to compare string values in the objects being sorted.
Note that localeCompare
takes into account various factors like accent marks, non-ASCII characters, and language-specific sorting rules.
Alternatives
If you're interested in exploring alternative approaches, consider:
Array.prototype.sort()
with custom sorting keys or behaviors.However, keep in mind that these alternatives might introduce additional dependencies, complexity, or performance overhead compared to the native sort using localeCompare
.