I am trying to find out which is more performant:
let array = [1,2,3,4]
array.includes(4)
or
let str = "1234";
str.includes(4);
and have tried to find it out by executing:
console.time();
let ar = [1,2,3,4,5];
ar.includes(4);
console.timeEnd();
console.time();
let str = "12345";
str.includes("4");
console.timeEnd();
in the console and from a script within the page. When directly executing from the console, the times are such that array.includes takes the least time. When executing from a page, the times reported are such that string.includes takes less time. What gives?!
Adding elements to a collectionpush array method is about 4 times faster than the . add set method, no matter the number of elements being added.
indexOf() The Array#indexOf() function is a common alternative to includes() . The indexOf() function returns the first index in the array at which it found valueToFind , or -1 otherwise.
Using Sets in ES6 to produce lists of unique objects is faster than using arrays, and less error prone than using objects.
includes() method is the fastest way to check if a JavaScript array contains an item, unless you have an array with a lot of items. In most cases, . includes() is both more readable and faster than for , so definitely use .
With small number of values to test against:
Conclusion: array.includes
is faster than string.includes
Then I tried increasing the number of values to ~100:
Ended up with same results: array.includes
is faster than string.includes
If you are interested in the implementation algorithm you can look at it here:
PS: In your case, I think the variable declaration is taking more time in Array Incldues test than string declaration. If you move the declaration out of the timer, you should also see consistent results.
Proof:
String declaration takes 1/10th the time that it takes to declare an array
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With