var itemsCount = 1e2;
var items = Array.from({ length: itemsCount }, () => Math.floor(Math.random() * itemsCount));
items.reduce((list, item) => list.indexOf(item) > -1 ? list : [list, item], []);
function unique(arr) {
var hash = {}, result = [];
for ( var i = 0, l = arr.length; i < l; ++i ) {
if ( !hash.hasOwnProperty(arr[i]) ) {
hash[ arr[i] ] = true;
result.push(arr[i]);
}
}
return result;
}
unique(items)
function unique(arr) {
var hash = {}, result = [];
for ( var i = 0, l = arr.length; i < l; ++i ) {
if ( !hash.hasOwnProperty(arr[i]) ) {
hash[ arr[i] ] = true;
result[result.length] = arr[i];
}
}
return result;
}
unique(items)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Javascript Array.reduce/Array.indexOf | |
object literal/res.push(arr[i]); | |
object literal/res.length |
Test name | Executions per second |
---|---|
Javascript Array.reduce/Array.indexOf | 59695.1 Ops/sec |
object literal/res.push(arr[i]); | 371876.7 Ops/sec |
object literal/res.length | 370664.2 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition
The benchmark is designed to compare three approaches for creating an array with unique values:
Array.prototype.reduce()
: This method reduces an array by applying a function to each element, returning the first value that satisfies the condition.Lodash Uniq
(a library): Lodash Uniq is a utility function from the Lodash library that removes duplicate elements from an array.res.push()
method.result[result.length] = arr[i];
).Options Compared
The benchmark compares these four approaches:
Array.prototype.reduce()
: This approach is concise and efficient for creating an array of unique values. However, it may not be suitable for very large arrays due to performance overhead.res.push()
: This approach is straightforward but may lead to slower performance compared to other methods due to repeated push()
calls.result.length
: This approach is similar to the previous one but uses indexing instead of push()
. It might have a slight performance advantage, but it's still not as efficient as reduce()
.ExecutionsPerSecond
), which indicates how many times each approach can be executed in 1 second.Libraries and Special JS Features
Alternatives
Other approaches to creating an array of unique values might include:
Set
or Map
data structures, which provide built-in functionality for removing duplicates.However, these alternatives are not explicitly tested in this benchmark definition.