function generateRandomData(length) {
const data = [];
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++) {
let randomString = '';
for (let j = 0; j < 20; j++) {
randomString += characters.charAt(Math.floor(Math.random() * characters.length));
}
data.push({ value: randomString });
}
return data;
}
var data = generateRandomData(20);
var stringToBeChecked = data[15];
const a = data.map(x => x.value);
return a.includes(stringToBeChecked);
const b = new Set(data.map(x => x.value));
return b.has(stringToBeChecked);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
includes | |
lookup |
Test name | Executions per second |
---|---|
includes | 3932468.5 Ops/sec |
lookup | 615016.6 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition
The benchmark is designed to compare two approaches: using array.includes()
vs using a Set
data structure (set.has()
). The goal is to determine which approach is more efficient, especially when the dataset needs to be initialized every time.
Script Preparation Code
The script preparation code generates random data for testing. It creates an array of objects with random strings as values and stores it in the data
variable. The stringToBeChecked
variable is set to the 16th element of this array.
Html Preparation Code
There is no HTML preparation code, which means that the test cases are running in a JavaScript environment without any additional web page context.
Individual Test Cases
The benchmark consists of two individual test cases:
array.includes()
to search for the stringToBeChecked
value within the data
array.Set
data structure from the data
array and then uses set.has()
to check if the stringToBeChecked
value is present in the set.Library: Set
The Set
library is used in the second test case (lookup
). A Set
data structure is a collection of unique values that are ordered and cannot have duplicate keys. The has()
method checks whether an element with the specified value exists in the set or not.
Pros and Cons
Set
data structure when dealing with large datasets or repeated values.array.includes()
for large datasets, especially if the dataset is unordered or contains duplicates.Other Considerations
The benchmark may also take into account other factors that can affect performance, such as:
Alternatives
If you're interested in exploring alternative approaches, you could consider using:
However, these alternatives may not offer significant performance benefits over Set
or array.includes()
in this specific benchmark.