Which is more performant array.includes or string.includes?
With small number of values to test against:
- On Benchmark Suite: https://jsfiddle.net/533hc71h/464/
- On Node:
- On Chrome console:
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/
- Node
- Chrome console:
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:
String declaration takes 1/10th the time that it takes to declare an array
Based on the benchmark tests on different browser platforms it all depends on the Javascript Engine and runtime elements on that platforms (Windows, Mac or Ubuntu)
Chrome on Mac OS yielded Array.includes
faster than String.includes
well on Safari Mac OS it was opposite.(jsperf.com testcase created by @shashanka n)
and Node v8.0.0 on Mac OS string.includes
appear's faster than Array.includes
with result as below
Node test case source code:
let ar = [1,2,3,4,5];
console.time("Array");
ar.includes(4);
console.timeEnd("Array");
let str = "1,2,3,4,5";
console.time("String");
str.includes("4");
console.timeEnd("String");
The above testcase on Chrome
Sometimes test case ambiguity might cause different results. There's no definite method to pin the API's performance, all we can we can spare some milliseconds and live with that until it really matters or hampers the performance on larger-scale.