Crowley
Crowley

Reputation: 169

What solution performs faster for searching substring in JavaScript?

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?

Upvotes: 0

Views: 679

Answers (1)

Emil S. Jørgensen
Emil S. Jørgensen

Reputation: 6366

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);

Upvotes: 3

Related Questions