var list = [Array(1000).keys()].map((index) => {return {id: index, name: `PRODUCT_${index}`}});
var newItems = [{id: 50, name: 'CUST_50'}, {id: 412, name: 'CUST_412'}];
var newItemIds = newItems.map((item) => item.id);
list.filter((item) => {
return !newItemIds.includes(item.id);
});
list.filter((item) => {
return newItemIds.indexOf(item.id) === -1;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
includes | |
indexOf |
Test name | Executions per second |
---|---|
includes | 4397.2 Ops/sec |
indexOf | 4827.2 Ops/sec |
Let's break down the benchmark and its test cases.
What is being tested?
The provided JSON represents two microbenchmarks that compare the performance of two approaches: using the includes
method and using the indexOf
method to filter an array in JavaScript. The benchmarks are designed to measure the execution speed of these methods on a list of 1000 objects, where some items are already present in the list.
Options compared
The two test cases compare the performance of:
includes
function.Pros and Cons
indexOf
for large arrays because it requires iterating over the array until a match is found.includes
for large arrays because it returns an index immediately, reducing iteration time. Also, it's often more efficient for exact matches.Other considerations:
includes
and indexOf
.Library and syntax
Neither test case uses any external libraries or special JS features beyond standard JavaScript functionality.
Benchmark preparation code
The script preparation code creates an array list
with 1000 objects, each representing a product, and adds two new items (newItems
) that are not present in the list. The newItemIds
variable is created by mapping the id
property of newItems
to an array.
Benchmark execution
The benchmark is executed multiple times (not specified), and the results are collected for each test case. The latest available result shows:
includes
method, Chrome 76 on Linux desktop executes approximately 4827 executions per second.indexOf
method, Chrome 76 on Linux desktop executes approximately 4397 executions per second.Alternatives
Other alternatives to these methods might include: