<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.js"></script>
var elements = [1,2,3,1,2,4,2,3,5,3]
_.uniq(elements)
[new Set(elements)]
elements.filter((v, i, a) => a.indexOf(v) === i)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.uniq | |
set | |
uniq by filter |
Test name | Executions per second |
---|---|
_.uniq | 7902636.0 Ops/sec |
set | 4935947.0 Ops/sec |
uniq by filter | 11516957.0 Ops/sec |
I'll break down the explanation into smaller parts to make it easier to understand.
Benchmark Definition JSON
The provided JSON represents a benchmark test case for measuring the performance of JavaScript code that removes duplicate elements from an array. The test has three variants:
uniq
function (version 4.17.21).The script preparation code defines an array elements
with duplicate values, and the HTML preparation code includes the necessary Lodash library file (lodash.js
) version 4.17.21.
Options Compared
Each option has its pros and cons:
Lodash's uniq
function: This is a popular utility function that removes duplicates from an array while preserving order. The pros include:
Creating a new Set and spreading its elements: This approach is simple, efficient, and doesn't require any external libraries.
Filtering the original array: This approach uses a callback function to filter out duplicates while preserving the original array's order.
Library: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks like array manipulation, string manipulation, and more. The uniq
function is one of its most useful utilities for removing duplicates from arrays while preserving order.
Special JS Feature/ Syntax (None)
There are no special JavaScript features or syntaxes used in this benchmark test case.
Other Alternatives
If you need to measure the performance of other approaches, here are some alternatives:
Array.prototype.filter()
and Array.prototype.indexOf()
underscore
or ramda
Keep in mind that each approach has its own strengths and weaknesses, and the choice of which one to use depends on your specific requirements and preferences.