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?

3
  • 1
    measure it yourself. Commented Feb 15, 2017 at 13:43
  • Go to 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. Commented Feb 15, 2017 at 13:51
  • Use the search. It is a duplicate of stackoverflow.com/questions/5296268/… Commented Feb 15, 2017 at 13:51

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.