<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var arr = ['1', '2', '3', 'sfsfsfs', 'rfwfwqfwafw', 'wfwfwrfqfw', 'wfwfs6ht7jt', 'rgewsrfafa', 'fgdgfdhrhrt', 'egegregeee', 'wtgfwrfqwfw', 'yo8opl8ol8', 'wrfwqrfwfwe', 'wfw3tye55' ,'gegwsvfwrwfw' , 'rfwfwqfwafw'];
return [new Set(arr)]
return _.uniq(arr)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JS | |
Lodash |
Test name | Executions per second |
---|---|
JS | 1368129.5 Ops/sec |
Lodash | 2210791.2 Ops/sec |
Let's break down the provided JSON and explain what is tested on it.
Benchmark Definition
The benchmark definition represents two test cases:
return [...new Set(arr)];
This code creates a new array by spreading the contents of an existing array (arr
) into a new array, and then converts it to a set using the Set
constructor. The resulting array is returned.
return _.uniq(arr);
This code uses the _.uniq()
function from Lodash to create an array with unique elements, similar to the JavaScript version above.
Options Compared
The benchmark compares two options:
Pros and Cons of Each Approach
Library: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks such as array manipulation, object creation, and more. The _.uniq()
function used in this benchmark is one of these utility functions, designed to simplify the process of creating an array with unique elements.
Special JS Feature: ES6 Spread Operator
The code uses the ES6 spread operator ([...]
) to create a new array from an existing array. This feature was introduced in ECMAScript 2015 and has since become a standard part of JavaScript. The use of this feature allows for concise and expressive code, but may also introduce additional overhead or complexity depending on the browser's implementation.
Other Alternatives
If you're interested in exploring alternative approaches, here are a few options:
Set
or Lodash, you could use Array.prototype.reduce()
to achieve the same result.Array.prototype.filter()
to create an array with unique elements.I hope this explanation helps!