0

I need to check if some string contains another string (substring) so can someone tell me which one of this perform faster:

someString.includes(thisSubstring) or 
someString.indexOf(thisSubstring) !== -1 

It depends from the browser? Are there any faster solutions?

Crowley
  • 169
  • 6
  • 1
    measure it yourself. – Daniel A. White Feb 15 '17 at 13:43
  • Go to https://jsfiddle.net/, create a string, create a loop with a timer that iterates n times and performs n `includes` checks. Then another loop with a timer that performs n `indexof` checks. Then come back here, post the fiddle along with your answer of which one is faster. – Forklift Feb 15 '17 at 13:51
  • Use the search. It is a duplicate of http://stackoverflow.com/questions/5296268/fastest-way-to-check-a-string-contain-another-substring-in-javascript – Zefick Feb 15 '17 at 13:51

1 Answers1

3

indexOf is faster, but you could have easily run these test yourself.

In the future you can use the pattern below to measure execution time:

var str1 = "nananananaananana Catman!";
var str2 = "Catman!";
var max = 10000000;
var t = new Date();
for(var i = 0; i < max; i++) {
  str1.indexOf(str2) >= 0;
}
console.log("indexOf",new Date() - t);
t = new Date();
for(var i = 0; i < max; i++) {
  str1.includes(str2);
}
console.log("includes",new Date() - t);
t = new Date();
for(var i = 0; i < max; i++) {
  str1.indexOf(str2) >= 0;
}
console.log("indexOf",new Date() - t);
t = new Date();
for(var i = 0; i < max; i++) {
  str1.includes(str2);
}
console.log("includes",new Date() - t);
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28
  • 1
    @Prusse If this had been a question of higher complexity, i probably would, but with something this simple i wanted to give OP the tools to log however she/he pleases (private unittest, quick performance tests, etc.) by showcasing the simplest performance test pattern. – Emil S. Jørgensen Feb 16 '17 at 09:44