var nested = Array.from({
length: 10000
}).map(() => Math.floor(Math.random() * Math.floor(10)));
var list = [2,3,4,5];
nested.map(item => {
if (list.indexOf(item) === -1) {
list.push(item);
}
});
const selectedNested = nested.filter(item => list.indexOf(item) === -1);
list = list.concat(selectedNested);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
1 | |
2 |
Test name | Executions per second |
---|---|
1 | 621.3 Ops/sec |
2 | 671.9 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
The provided JSON represents a benchmark test case, which consists of two individual tests (or "test cases") that compare different approaches to achieve a specific goal. In this case, both tests aim to find elements in an array (list
) and add them to another array (nested
), if they are not already present.
Benchmark Definition
The benchmark definition is a JSON object that contains two scripts:
nested
array with 10,000 random integers between 0 and 9, inclusive. It then creates an initial list [2, 3, 4, 5]
.Individual Test Cases
The two test cases are defined as arrays of objects, each containing a Benchmark Definition
and a Test Name
. These definitions specify how to measure the performance of different approaches:
map()
method to iterate over the nested
array and add elements from the list
that are not already present in nested
.nested.map(item => {
if (list.indexOf(item) === -1) {
list.push(item);
}
});
filter()
method to remove elements from the nested
array that are not present in the list
, and then concatenates the filtered results with the list
.const selectedNested = nested.filter(item => list.indexOf(item) === -1);
list = list.concat(selectedNested);
Library Usage
In both test cases, a library is used:
map()
is a native JavaScript method.filter()
and concat()
are also native JavaScript methods.No external libraries are required to run these tests.
Special JS Features/Syntax
None of the provided code snippets utilize special JavaScript features or syntax. They are straightforward examples that demonstrate the use of basic array methods.
Pros and Cons
Here's a brief analysis of each approach:
map()
method.list
) that needs to be sorted in place, which can be expensive for large inputs.list
.filter()
and concat()
), which might introduce additional overhead.Other Alternatives
If you're interested in exploring alternative approaches, here are a few suggestions:
list
instead of an array.Keep in mind that these alternatives might introduce additional complexity and may not always provide better performance. The best approach will depend on the specific use case and requirements of your project.