function getArray(length) {
const result = [];
for (let i = 0; i < length; i++) {
result.push(i + 'abc'); // In case the browser does some sort of optimization for arrays with only integers ¯\_(ツ)_/¯
}
return result;
}
function getRandomTargetElement(arrayLength) {
const index = Math.floor(Math.random() * arrayLength);
return index + 'abc';
}
array_small = getArray(10000);
array_large = getArray(1000000);
set_small = new Set(array_small);
set_large = new Set(array_large);
array_small.includes(getRandomTargetElement(10000));
array_large.includes(getRandomTargetElement(1000000))
set_small.has(getRandomTargetElement(10000))
set_large.has(getRandomTargetElement(1000000))
const target = getRandomTargetElement(10000);
const set = new Set(array_small);
set.has(target)
const set = new Set(array_small);
for (let i = 0; i < 100; i++) {
const target = getRandomTargetElement(10000);
set.has(target)
}
for (let i = 0; i < 100; i++) {
const target = getRandomTargetElement(10000);
array_small.includes(target)
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.includes, 10 000 elements | |
Array.includes, 1 000 000 elements | |
Set.has, 10 000 elements | |
Set.has, 1 000 000 elements | |
Array to Set + Set.has, 10 000 elements | |
Array to Set + Set.has x 100, 10 000 elements | |
Array.includes x 100, 10 000 elements |
Test name | Executions per second |
---|---|
Array.includes, 10 000 elements | 95126.7 Ops/sec |
Array.includes, 1 000 000 elements | 958.7 Ops/sec |
Set.has, 10 000 elements | 38336568.0 Ops/sec |
Set.has, 1 000 000 elements | 26425542.0 Ops/sec |
Array to Set + Set.has, 10 000 elements | 2759.9 Ops/sec |
Array to Set + Set.has x 100, 10 000 elements | 2739.9 Ops/sec |
Array.includes x 100, 10 000 elements | 966.3 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Overview
The benchmark measures the performance difference between array.includes()
and set.has()
operations on large arrays and sets.
Options Compared
Two options are compared:
Pros and Cons of Each Approach:
array.includes()
for large datasetsOther Considerations:
getArray()
function. This ensures consistent input data for each test case.getRandomTargetElement()
function generates random targets for the includes() and has() operations, reducing any potential optimizations that might favor specific values.Library Use:
The benchmark uses the Set
object to represent sets. The Set
class is a built-in JavaScript object that provides an efficient way to store unique values.
Special JS Features/Syntax (None Mentioned):
No special JavaScript features or syntax are used in this benchmark.
Alternatives:
If you're interested in exploring other benchmarking tools, consider the following alternatives: