<!--your preparation HTML code goes here-->
var data = []
for (let i = 0; i < 5000; ++i) data.push({ username: 'toto' })
data.push({ username: 'titi' })
for (let i = 0; i < 2500; ++i) data.push({ username: 'toto' })
data.some((e) => e.username === 'titi')
data.map((e) => e.username).includes('titi')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
.some() | |
.map().includes() |
Test name | Executions per second |
---|---|
.some() | 248658.1 Ops/sec |
.map().includes() | 26016.1 Ops/sec |
The benchmark compares the performance of two different approaches for checking if an element exists in an array of objects in JavaScript. The specific methods being tested are .some()
and the combination of .map().includes()
.
.some()
Method:
data.some((e) => e.username === 'titi')
.some()
method tests whether at least one element in the array passes the test implemented by the provided function. It returns true
as soon as it finds an element that meets the condition, otherwise it returns false
..map().includes()
Combination:
data.map((e) => e.username).includes('titi')
.map()
method. Then it checks if the username 'titi' exists in this new array using the .includes()
method..some()
Method:
.map().includes()
Combination:
.map().includes()
requires additional memory for storing the transformed array, which can be a significant factor in cases with large datasets..map().includes()
can enhance readability for some engineers, it sacrifices performance in a straightforward presence check, especially evident in the benchmark results where .some()
executed significantly more times per second than the .map().includes()
approach.The benchmark results reflect these differences clearly:
.some()
method achieved an impressive 248,658.14 executions per second..map().includes()
method only managed 26,016.13 executions per second, highlighting the performance cost associated with creating an intermediate array.In addition to the two methods tested:
.filter()
: This method could also be used, allowing filtering based on the condition, but is less efficient for this purpose than .some()
.for
loop can be quite performant as well for simple checks, allowing for early exits upon finding a match like .some()
.Understanding these differences enables developers to make informed choices based on their specific needs for performance, readability, and memory efficiency.