const nonUnique = ['one', 'two', 'three', 'three', 'four', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
const unique = Object.keys(nonUnique.reduce((acc, item) => {
if (!acc[item]) {
acc[item] = true
};
return acc;
}, {}));
const nonUnique = ['one', 'two', 'three', 'three', 'four', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
const unique = Array.from(new Set(nonUnique));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using an object | |
Using a Set |
Test name | Executions per second |
---|---|
Using an object | 3243160.8 Ops/sec |
Using a Set | 3800777.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks and explore what's being tested in this benchmark.
Benchmark Overview
This benchmark compares two approaches to remove duplicate strings from an array: using an object and using a Set. The goal is to create a unique array of strings from a possible non-unique array.
Options Compared
Two options are compared:
Object.keys()
method to get an array of unique keys from an object, where each key is a string. The reduce()
method is used to iterate over the original array and add each item to the object only if it's not already present.Set
data structure to automatically eliminate duplicates. It converts the array to a Set using Array.from(new Set(nonUnique))
, which returns an array of unique strings.Pros and Cons
Using an Object:
Pros:
Cons:
Using a Set:
Pros:
Cons:
Set
data structure, which may not be available in older browsers or environments.Other Considerations
When choosing between these two approaches, consider the specific requirements of your use case. If you need to handle non-unique arrays with arbitrary key values, using an object might be a better choice. However, if performance is critical and you're working with large datasets, using a Set could be a better option.
Library/Dependencies
Neither of these approaches requires any additional libraries or dependencies beyond what's built into JavaScript. However, the Set
data structure is optimized for specific browsers and environments, so it may not work correctly in older or less-capable browsers.
Special JS Feature/Syntax
The reduce()
method and the Object.keys()
method are part of the standard JavaScript syntax. However, some features like array destructuring (Array.from(new Set(nonUnique))
) might be more recent additions to the language, introduced in ECMAScript 2015 (ES6).