Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.includes() algorithm and speed?

I'm interested to know what algorithm the .includes() method uses? Does it use a modularized hash like rabin karp?

I'm somewhat hesitant to use .includes() without knowing more about its methodology and speed. The documentation I've found doesn't go into specifics when discussing it (e.g. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes)

like image 974
Babra Cunningham Avatar asked Feb 05 '23 17:02

Babra Cunningham


1 Answers

Given that different engines could implement .includes in different ways, it may be difficult to make blanket statements regarding implementation. However it should be possible to get an idea of it's speed by doing some benchmarking (as testing is likely the only way to be sure).

Using node 7.0 I tried testing three different functions:
1. includes(), passing in a sequential array
2. a basic for loop, passing in a sequential array
3. has(), passing in a precreated set from a sequential array

The results I obtained suggested the length of the array itself didn't seem to matter(as hoped), but how far the desired number was from the start did. For finding numbers at indexes <20 or so, the for loop seems slightly faster (by perhaps ~15%?). For larger indexes includes() over takes the for loop (being ~2-3x times faster by index 500 seemingly). However .has() is vastly faster for finding numbers at later indexes (~25-30x faster by index 800) and the size of the indexes seems to have little impact on its speed (but creating the set takes time).

Admittedly these are somewhat limited tests and many factors could impact them. One interesting result was that if a set was created from the passed in array (and not some other array), even if the set wasn't passed into the functions, it seemed to increase the speed of includes, and decrease the speed of the for loop function slightly. Some type of caching which somehow benefits .includes() I'd assume?

like image 157
Immaterial Avatar answered Feb 10 '23 23:02

Immaterial