<!--your preparation HTML code goes here-->
const fruits = ['apple', 'banana', 'orange', 'grape'];
fruits.includes('banana');
fruits.indexOf('orange');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
includes | |
indexof |
Test name | Executions per second |
---|---|
includes | 82131280.0 Ops/sec |
indexof | 78774944.0 Ops/sec |
The benchmark you are examining compares two methods for determining the presence of an element within an array in JavaScript: Array.prototype.includes()
and Array.prototype.indexOf()
.
Array.prototype.includes()
:
includes
fruits.includes('banana');
true
if found, otherwise false
. It is particularly useful for readability, as the intention of checking for existence is clear from the method name itself.Array.prototype.indexOf()
:
indexof
fruits.indexOf('orange');
-1
if it is not found. While indexOf()
can achieve the same goal as includes()
by checking for a return value of -1
, it is not as semantically clear for checking existence.From the benchmark results:
includes
method achieved 93,520,256 Executions Per Second.indexOf
method achieved 76,465,608 Executions Per Second.includes()
includes()
is faster, but there might be rare scenarios where older engines or implementations could see differing performance.indexOf()
-1
for checks, which can lead to less readable code.includes()
.Readability vs. Performance: While includes()
shows better performance in this benchmark, the clarity it brings often makes it the preferred choice in modern JavaScript applications. Performance can be a significant factor in tightly looped operations or performance-critical sections.
Polyfills: For coding in environments that do not support ES6, developers may need polyfills for includes()
to bring compatibility, whereas indexOf()
remains widely supported.
Using a Set: If you often need to check for membership, considering a Set
might be advantageous. Creating a Set
from an array allows for O(1) average time complexity for lookups, but it does come at the cost of increased memory usage.
For Loop: Manual iteration over the array with a for
loop to find a value can be a last resort. While this provides maximum flexibility (like breaking early), it typically results in less readable and more error-prone code.
Higher-Order Functions: Methods like Array.prototype.some()
can check for existence by running a function on each element, which can be more readable in more complex conditions, but may sacrifice performance as compared to direct methods.
By comparing includes()
and indexOf()
, developers can choose which method better fits their needs based on the context of the application and the importance of performance versus readability.