Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more performant array.includes or string.includes?

Tags:

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?!

like image 529
shashanka n Avatar asked Jun 27 '17 04:06

shashanka n


People also ask

Is set Has faster than array includes?

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.

What to use instead of array includes?

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.

Is JavaScript set faster than array?

Using Sets in ES6 to produce lists of unique objects is faster than using arrays, and less error prone than using objects.

Does JavaScript include fast?

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 .


1 Answers

With small number of values to test against:

  • On Benchmark Suite: https://jsfiddle.net/533hc71h/464/
  • On Node: String includes vs Array includes
  • On Chrome console: Chrome1

Conclusion: array.includes is faster than string.includes

Then I tried increasing the number of values to ~100:

  • On Benchmark Suite: https://jsfiddle.net/533hc71h/465/
  • NodeBig Comparison
  • Chrome console: Chrome comparison

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:

  • Array includes: http://www.ecma-international.org/ecma-262/7.0/#sec-array.prototype.includes
  • String includes: https://tc39.github.io/ecma262/#sec-string.prototype.includes

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: Proof

String declaration takes 1/10th the time that it takes to declare an array

like image 118
Aftab Khan Avatar answered Oct 16 '22 06:10

Aftab Khan